Angular2:答应退货

Angular2: Promise return

本文关键字:答应 Angular2      更新时间:2023-09-26

我想从我的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 );
      });
}

Promisethen(...)的目的是使能链接调用,以便在前一个调用完成时执行下一个调用。

异步执行意味着将调用排入事件队列,然后执行同步代码(console.log()(。传递给.then(...)的代码最终在Promise解析时执行(通常在来自服务器的响应到达时(。