[英]Angular2: Promise return
I want to get the comments from my API. 我想从我的API中获取评论。 So, the function should promise a return?
那么,函数应该承诺返回吗? What is better?
什么是更好的? Clasic or promise return?
求索还是承诺回报?
And I have still a problem, the promise return return undefined. 而且我还有一个问题,promise return未定义返回。
comments.component.ts 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 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}
];
And I get in console these: 然后进入控制台,这些是:
valoare
瓦洛雷
Array [ Object ]
数组[对象]
undefined
未定义
You need to move the code inside the then(...)
(same for observables with subscribe(...)
您需要将代码移动到
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 );
});
}
The purpose of Promise
and then(...)
is to enable to chain calls so that a subsequent call is executed when the previous one completes. Promise
和then(...)
的目的是启用链接调用,以便在前一个调用完成时执行后续调用。
Async execution means that the call is enqueued into the event queue and sync code (your console.log()
) is executed next. 异步执行意味着将调用排队到事件队列中,然后再执行同步代码(您的
console.log()
)。 The code passed to .then(...)
is eventually executed when the Promise
resolves (usually when the response from the server arrives). 当
Promise
解析时(通常在服务器的响应到达时),最终将执行传递给.then(...)
的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.