Angular2:答应退货
Angular2: Promise return
我想从我的API获得注释。那么,函数应该承诺返回吗?什么更好?冲突还是承诺回归?
我还有一个问题,承诺返回未定义。
注释.组件.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;
}
}
注释.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
阵列[对象]
未定义
您需要在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
解析时执行(通常在来自服务器的响应到达时(。
相关文章:
- 如何在Angular2中使用jQuery插件
- 不能从angular2中的子组件指定父组件中的数组
- 如何为生产构建angular2应用程序
- 使用javascript协调angular2组件
- Angular2将组件方法导入到另一个组件中
- Angular2在装载前
- Angular2/JavaScript-如何显示localStorage保存的所有变量并获取所有键的总长度
- 基于路由的CSS样式-Angular2
- Angular2 ngFor—已选择集
- Angular2他们如何保存到缓存
- Angular2 rc1, where is shims_for_IE
- angular2中的全局服务不工作
- 如何在重建URL后从URL中传递过滤值,目的是使用Angular2和Typescript实现无限滚动
- Angular2-RadioButtonState未按预期工作
- Angular2-*ngIf:如何显示特定元素
- Angular2-TypeError:无法读取属性'Id'(Typescript)中未定义的
- Angular2/JavaScript-按1递增/递减(单击)
- Angular2组件未从视图中呈现javascript
- 如何将此JS翻译成Angular2
- Angular2:答应退货