[英]Angular2: Promise return
我想從我的API中獲取評論。 那么,函數應該承諾返回嗎? 什么是更好的? 求索還是承諾回報?
而且我還有一個問題,promise return未定義返回。
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;
}
}
評論
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}
];
然后進入控制台,這些是:
瓦洛雷
數組[對象]
未定義
您需要將代碼移動到then(...)
(對於帶subscribe(...)
可觀察對象相同
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 );
});
}
Promise
和then(...)
的目的是啟用鏈接調用,以便在前一個調用完成時執行后續調用。
異步執行意味着將調用排隊到事件隊列中,然后再執行同步代碼(您的console.log()
)。 當Promise
解析時(通常在服務器的響應到達時),最終將執行傳遞給.then(...)
的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.