2016-10-14 173 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来处理这个问题。再次感谢您的帮助! –