2016-10-14 171 views
0

我正在使用Angular 2.1.0,並且在嘗試創建HTTP服務以調用服務器提供的REST API時遇到問題。我用Google瀏覽過很多東西,並閱讀了很多關於如何做到這一點的文章,但是我已經把東西搞砸了。問題在於,它看起來像我的HTTP服務正在正確運行並從REST API獲取數據。我的組件訂閱服務返回的observable,但數據永遠不會被分配給組件變量,並且我的模板爆炸說我試圖從NULL獲取屬性。Angular 2 HTTP服務問題

這裏是我的服務代碼:

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); 
    } 
} 

這裏是我的組件代碼:

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> 

任何幫助,指針或想法將不勝感激!

由於提前, 道格

回答

2

你需要讓auth_infonull,因爲http調用是異步的。您可以通過在將屬性與模板綁定的位置之前添加*ngIf或通過在屬性名稱中添加?來實現此目的:auth_info?.auth_displayname

+0

Dave,感謝您的回覆,我不知道「?」功能模板(Angular仍然很新穎),這很好理解。你說的話很有道理,因爲auth_info是通過異步函數調用「餵食」的,我錯誤地認爲使用Observable來處理這個問題。再次感謝您的幫助! –