0
我想从我的API获取评论。 那么,函数应该答应一个return? 有什么更好?克拉克还是承诺回报?Angular2:Promise return
而且我还有一个问题,promise返回undefined。
comments.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}
];
和我在控制台这些:
valoare
数组[对象]
不确定
如果回复承诺或明确的价值会更好吗?只有在需要进行异步调用(不能返回普通值)时才使用承诺,否则同步执行总是首选,除非您明确希望由于某种原因执行异步调用。 –
我在Angular网站上看到这个例子..我刚才问,你知道为什么不工作?我喜欢在角度网站上。 –
在Angular网站上,他们模拟异步调用,以便演示如何应对异步执行。这并不意味着它是首选。 –