【问题标题】:Angular 2 HTTP service problemsAngular 2 HTTP 服务问题
【发布时间】:2016-10-14 22:16:09
【问题描述】:

我正在使用 Angular 2.1.0,但在尝试创建 HTTP 服务以调用我的服务器提供的 REST API 时遇到问题。我使用 Google 环顾四周,阅读了很多关于如何做到这一点的文章,但我搞砸了一些事情。

问题出在这里,看起来我的 HTTP 服务运行正常并从 REST API 获取数据。我的组件订阅了服务返回的 observable,但数据从未分配给组件变量,并且我的模板爆炸说我正在尝试从 NULL 获取属性。

这是我的服务代码:

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>

我可以尝试什么来解决这个问题?

【问题讨论】:

    标签: angular rxjs angular-http


    【解决方案1】:

    您需要允许 auth_infonull,因为 http 调用是异步的。您可以通过在将属性绑定到模板的位置之前添加*ngIf 或在属性名称中添加? 来做到这一点:auth_info?.auth_displayname

    【讨论】:

    • 戴夫,感谢您的回复,我不知道“?”模板中的功能(对于 Angular 来说仍然很新),这很高兴知道。您所说的很有意义,因为 auth_info 是由异步函数调用“提供”的,我(错误地)认为使用 Observable 可以解决这个问题。再次感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多