2016-08-05 55 views
0

我想從我的API獲取評論。 那麼,函數應該答應一個return? 有什麼更好?克拉克還是承諾回報?Angular2:Promise return

而且我還有一個問題,promise返回undefined。

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

數組[對象]

不確定

+0

如果回覆承諾或明確的價值會更好嗎?只有在需要進行異步調用(不能返回普通值)時才使用承諾,否則同步執行總是首選,除非您明確希望由於某種原因執行異步調用。 –

+0

我在Angular網站上看到這個例子..我剛纔問,你知道爲什麼不工作?我喜歡在角度網站上。 –

+0

在Angular網站上,他們模擬異步調用,以便演示如何應對異步執行。這並不意味着它是首選。 –

回答

1

您需要與subscribe(...)

移動代碼裏面 then(...)(同爲觀測
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解析時(通常是來自服務器的響應到達時)執行。

相關問題