我想从我的API获取评论。 那么,函数应该承诺返回? 什么是更好的? Clasic还是承诺回归?
我还有一个问题,承诺返回未定义。
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
Array [Object]
未定义
答案 0 :(得分:1)
您需要在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()
)。传递给.then(...)
的代码最终在Promise
解析时执行(通常在服务器响应到达时)。