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網站上,他們模擬異步調用,以便演示如何應對異步執行。這並不意味着它是首選。 –