2016-10-14 9 views
0

私はAngular 2.1.0で作業していますが、私のサーバーで提供されているREST APIを呼び出すHTTPサービスを作成しようとして問題が発生しています。私はGoogleを使って多くのことを見てきましたし、これを行う方法について多くの記事を読んでいますが、何か問題がありました。ここに問題があります、私のHTTPサービスが正しく動作しているように見えて、REST APIからデータを取得しています。私のコンポーネントは、サービスから返されたオブザーバブルにサブスクライブしますが、データはコンポーネント変数に割り当てられません。私のテンプレートは、私がNULLから属性を取得しようとしているということを爆発させます。ここで角2のHTTPサービスの問題

は私のサービスコードです:

import { Component, OnInit, OnDestroy } from '@angular/core'; 
import { Subscription } from 'rxjs/Subscription'; 
import { AuthenticationService } from '../services/authentication.service'; 
import { AuthInfoInterface } from '../interfaces/authentication'; 

@Component({ 
    selector: 'authentication', 
    templateUrl: 'authentication.component.html', 
    styleUrls: ['authentication.component.scss'], 
    providers: [AuthenticationService] 
}) 
export class AuthenticationComponent implements OnInit, OnDestroy { 
    showLogin: boolean = true; 
    auth_info: AuthInfoInterface; 
    subscription: any; 

    constructor(private authenticationService: AuthenticationService) { 
    } 
    getAuthentication() { 
    this.subscription = this.authenticationService.get() 
     .subscribe(
     auth_info => this.auth_info = auth_info, 
     err => console.error('Error: ' + err) 
    ); 
    } 
    ngOnInit() { 
    this.getAuthentication(); 
    } 
    ngOnDestroy() { 
    this.subscription.unsubscribe(); 
    } 
} 

そして、ここでは私の簡略化されたテンプレートのコードです:

<div> 
    {{auth_info.auth_displayname}} 
    </div> 

すべてのヘルプ、ポインタ

import { Injectable } from '@angular/core'; 
import { Http, Response, URLSearchParams } from '@angular/http'; 
import { Observable } from 'rxjs/Rx'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

import { AuthInfoInterface } from '../interfaces/authentication'; 

@Injectable() 
export class AuthenticationService { 
    private url: string = 'api/authentication'; 

    constructor (private http: Http) {} 

    get(): Observable<AuthInfoInterface> { 
    let params = new URLSearchParams(); 

    params.set("redirect", "false"); 
    params.set("passive", "true"); 
    return this.http.get(this.url, {search: params}) 
     .map((res: Response) => res.json()) 
     .catch(this.handleError); 
    } 
    handleError(error: any) { 
    let errorMsg = error.message || 'Server Error!'; 
    console.error(errorMsg); 
    return Observable.throw(errorMsg); 
    } 
} 

そして、ここでは私のコンポーネントのコードがありますまたはアイデアが大いに評価されるだろう!事前に

おかげで、 ダグ

答えて

2

httpコールが非同期であるので、あなたは、auth_infonullことを許可する必要があります。テンプレートにプロパティをバインドする場所の前に*ngIfを追加するか、プロパティ名に

+0

を追加することで、これを行うことができます。回答ありがとうございました。テンプレートの機能(まだAngularにはかなり新しい)、それは知っておくと良いです。 auth_infoが非同期関数呼び出しによって "フィード"されると、あなたが言っていることは意味をなさないので、私はObservableを使ってそれを処理したという印象の下で(誤って)でした。もう一度、役に立つお返事をいただきありがとうございます! –