【发布时间】:2016-08-06 00:34:24
【问题描述】:
我想从我的 API 中获取 cmets。 那么,该函数应该承诺返回吗? 什么是更好的?经典还是承诺回归?
我还有一个问题,promise return return undefined。
cmets.component.ts
import { Component, OnInit } from '@angular/core';
import { CommentService } from '../services/comment.service';
import { Comment } from '../class/Comment';
@Component({
template: 'dadada',
providers: [CommentService]
})
export class CommentsComponent implements OnInit {
coms: Comment[];
constructor(private commentService: CommentService) {
}
ngOnInit() {
console.log( this.commentService.testfunction() );
this.commentService.get_all_comments().then((data) => {
this.coms = data;
});
console.log ( this.commentService.get_all_comments2() );
console.log ( this.coms );
}
}
comment.service.ts
import { Injectable } from '@angular/core';
import { Comment, Comments } from '../class/Comment';
@Injectable()
export class CommentService {
testfunction() {
return 'valoare';
}
get_all_comments() {
return Promise.resolve(Comments);
}
get_all_comments2() {
return Comments;
}
}
Comment.ts
export class Comment {
id: number;
text: string;
author: string;
created_at: number;
updated_at: number;
}
export const Comments: Comment[] = [
{id: 1, text: 'Look I am a test comment.', author: 'Chris Sevilleja', created_at: 0, updated_at: 0}
];
然后我进入控制台:
价值
数组[对象]
未定义
【问题讨论】:
-
这个问题真的是返回一个承诺还是一个简单的值更好?仅当您需要进行异步调用(无法返回纯值)时才使用 Promise,否则始终首选同步执行,除非您出于任何原因明确想要执行异步操作。
-
我在 Angular 网站上看到了这个例子。我只是问,你知道为什么不起作用吗?我确实喜欢角度网站..
-
在 Angular 站点上,他们模拟了一个异步调用,用于演示如何处理异步执行。这并不意味着它是首选。
标签: javascript service angular promise