【问题标题】:Angular2: Promise returnAngular2:承诺回报
【发布时间】:2016-08-06 00:34:24
【问题描述】:

我想从我的 API 中获取 cmets。 那么,该函数应该承诺返回吗? 什么是更好的?经典还是承诺回归?

我还有一个问题,promise return return undefined。

cmets.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}
];

然后我进入控制台:

价值

数组[对象]

未定义

【问题讨论】:

  • 这个问题真的是返回一个承诺还是一个简单的值更好?仅当您需要进行异步调用(无法返回纯值)时才使用 Promise,否则始终首选同步执行,除非您出于任何原因明确想要执行异步操作。
  • 我在 Angular 网站上看到了这个例子。我只是问,你知道为什么不起作用吗?我确实喜欢角度网站..
  • 在 Angular 站点上,他们模拟了一个异步调用,用于演示如何处理异步执行。这并不意味着它是首选。

标签: javascript service angular promise


【解决方案1】:

您需要将代码移动到 then(...) 中(对于带有 subscribe(...) 的 observables 也是如此

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 解析时执行(通常是在服务器响应到达时)。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2023-03-26
    • 2016-10-20
    • 1970-01-01
    • 2017-02-17
    • 1970-01-01
    • 2018-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多