无法绑定json数据以查看Angularjs2

时间:2016-10-18 10:15:32

标签: angular angular2-template

我正在尝试将json数据绑定到模板,但我不断收到一些例外情况。这是我的代码:

account.ts

export interface Account{
    AccountType:string;
    AmountHeld:string;
    AvailableBalance:string;    
}

account.service.ts

import { Injectable, Inject } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import {Account} from '../models/account';
import { Cookie } from 'ng2-cookies/ng2-cookies';

const URL = "http://payd.azurewebsites.net/api/User/1/account";

const AUTH = Cookie.get('token');

@Injectable()
export class AccountService {

  private accounts;

  constructor(private http: Http) {

  }

  httpGet(): Observable<Account> {
  var headers = new Headers();
  headers.append('Authorization', 'bearer ' + AUTH);
  //headers.append('Content-Type', 'application/x-www-form-urlencoded');

  return this.http.get(URL, {
     headers: headers
  }).map((response: Response) => response.json());
 }
}

account.component.ts

import { Component, OnInit } from '@angular/core';
import {AccountService} from '../services/account.service';
import { HttpClient } from '../providers/http-client';
import {Account} from '../models/account';

@Component({
  selector: 'app-account',
  templateUrl: './account.component.html',
  //styleUrls: ['./account.component.css'],
})
export class AccountComponent implements OnInit {

  private accounts:Account;
  private AccountType;
  private AmountHeld;
  private AvailableBalance;

  constructor(private _service:AccountService) {

  }

  ngOnInit() {    
    this._service.httpGet().subscribe(accounts=>{
      this.accounts=accounts;
    });
  }
}

account.component.html

<ul>
  <li>
    {{accounts.AccountType}}
  </li>
</ul>

我成功获得了json,我可以在浏览器工具中看到它。但是,当我尝试将数据绑定到模板时,我收到此错误:

  

EXCEPTION:未捕获(在承诺中):错误:./AccountComponent类中的错误AccountComponent - 内联模板:9:6导致:self.context.accounts未定义。

我是Angular 2的新手,感谢任何帮助。提前致谢!

2 个答案:

答案 0 :(得分:1)

您必须使用*ngIf指令或Elvis运算符(?)来保护&#34;您的模板,直到从Web API加载数据。

* ngIf指令

<ul *ngIf="accounts">
  <li>
      {{accounts.AccountType}}
  </li>
</ul>

猫王(?)运营商

<ul>
  <li>
      {{accounts?.AccountType}}
  </li>
</ul>

您收到当前错误是因为您尝试显示accounts.AccountTypeaccounts变量为undefined(尚未从网络API接收数据)。

答案 1 :(得分:0)

您可以使用RouterModule的resolve属性附带新的@angular/router": "3.0.0"包。

在您通过API获取JSON数据后,将加载路径组件。

{ 
  path: ':id',
  component: CrisisDetailComponent,
  resolve: {
     crisis: CrisisDetailResolve
  }
}

检查Angular Example - Router是否有实施。

希望有所帮助!