2017-01-31 20 views
0

おやすみなさいangular2 http解決約束

私はangular2に入ってみようとしています。

サービス:

getProject(id: number): any { 
    var url = this.ProjectsUrl + '/'+ id; 
    return this.http.get(url) 
     .toPromise() 
     .then(response => { 
     console.log(response.json().data as Project); 
     }) 
     .catch(this.handleError); 
    } 

コンポーネント:

getProject(id:number){ 
     this.projectService 
     .getProject(id) 
     .then(project => this.project = project); 
    } 

ngOnInit()

ngOnInit() { 
    this.sub = this.route.params.subscribe(params => { 
     this.getCustomers(); 
     console.log('b4 getProj') 
     this.getProject(+params["id"]); 
     console.log('after getProj') 
    }); 
    } 

出力:

b4 getProj 
after getProj 
Object { Project } 

私は約束がなぜ解決されないのか理解できませんか?任意のヒント?

+0

をなぜあなたは何かが解決されないと思いますか? –

答えて

0

私は、これはあなたが望むものであると思います:Angular2と

getProject(id:number){ 
    return this.projectService // <<<=== added return 
     .getProject(id) 
     .then(project => this.project = project); 
    } 

    ngOnInit() { 
    this.sub = this.route.params.subscribe(params => { 
     this.getCustomers(); 
     console.log('b4 getProj') 
     this.getProject(+params["id"]) 
     .then(_ => console.log('after getProj')); // <<<=== changed 
    }); 
    } 
+0

答えてくれてありがとうGünter。明日これを試してみるつもりです。しかし、私が投稿したスニペットが他のすべてのhttp-Requestでも動作するのはなぜですか? – devphil0

+0

これはちょうど推測です。私はあなたの質問から、問題が何であるかを知ることができませんでした。 –

1

一つの良いところは、約束の場所で観測への支援です。あなたは、コードの下に約束の場所で観測を使用したい場合に使用することができます念の

サービス:

getProject(id: number): any { 
    var url = this.ProjectsUrl + '/'+ id; 
    return this.http.get(url) 
     .map(response => { 
     response.json().data as Project; 
     }) 
     .catch(this.handleError); 
    } 

はコンポーネント:

getProject(id:number){ 
      this.projectService 
      .getProject(id) 
      .subscribe(project => { 
      this.project = project 
      }); 
     } 

私はこれが役に立てば幸い。

ちょうどあなたのサービスでは、次の宣言を追加することを忘れないでください:

import { Observable } from 'rxjs'; 
+0

あなたのanwserにありがとうたくさん。私が進める前に、私はこれら2つの方法の違いを得る必要があると思う。 – devphil0

+0

もちろん、問題ありません。 –