Angular 2:{{object}}起作用,{{object.child}}抛出错误 [英] Angular 2: {{object}} works, {{object.child}} throws error

查看:75
本文介绍了Angular 2:{{object}}起作用,{{object.child}}抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经和Angular v1合作已经有一段时间了,自从Angular v2进入测试阶段以来,一直在玩这个。

Been working with Angular v1 for some time now and since Angular v2 came in Beta, been playing around with that.

现在我有了这段代码,但不能让它上班,真的不知道为什么。不知何故,当我打印 {{profileUser | json}} 一切正常(profileUser是一个对象)。

Now I've got this piece of code, but can't get it to work, really don't know why. Somehow, when I print {{profileUser | json}} everything works fine (profileUser is an object).

但是当我想打印那个对象的子节点时(例如 {{profileUser.name}} {{profileUser.name.firstName}} ),Angular会抛出以下错误:

But when I want to print a child of that object (for example {{profileUser.name}} or {{profileUser.name.firstName}}), Angular throws the following error:

EXEPTION:TypeError:undefined不是ProfileComponent @中{{{profileUser.name}}中的对象(评估'l_profileUser0.name') 4:11

这对我来说真的很混乱,应该只是最简单的事情之一..刚开始使用TypeScript btw ..

It's really confusing to me, should be just one of the simplest things around.. Just started with TypeScript btw..

这是一些代码 - ProfileService.ts

Here is some code - ProfileService.ts:

import { Injectable } from 'angular2/core';
import { Headers } from 'angular2/http';
import { API_PREFIX } from '../constants/constants';
import { AuthHttp } from 'angular2-jwt/angular2-jwt';
import 'rxjs/add/operator/map';

@Injectable()
export class ProfileService {

  API_PREFIX = API_PREFIX;

  constructor(private _authHttp:AuthHttp) {
  }

  getProfileData(username:string):any {
    return new Promise((resolve, reject) => {
      this._authHttp.get(API_PREFIX + '/users/username/' + username)
        .map(res => res.json())
        .subscribe(
          data => {
            resolve(data.data);
          },
          err => {
            reject(err);
          }
        )
      ;
    });
  }
}

这是我的 ProfileComponent

import {Component, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {ProfileService} from '../../services/profile.service';

@Component({
  selector: 'profile',
  templateUrl: './components/profile/profile.html',
  directives: [],
  providers: [ProfileService]
})

export class ProfileComponent implements OnInit {

  public username:string;
  public profileUser:any;

  constructor(private _profileService: ProfileService,
              private _params: RouteParams) {
    this.username = this._params.get('username');
  }

  ngOnInit() {
    this.getProfileData(this.username);
  }

  getProfileData(username:string):void {
    this._profileService.getProfileData(username)
      .then(data => {
        this.profileUser = data;
        console.log(data);
      })
    ;
  }
}

最后,个人资料。 html 模板:

<pre> <!-- works! -->
{{profileUser | json}}
</pre>

或..

<pre> <!-- throws the error -->
{{profileUser.name | json}}
</pre>

或..

<pre> <!-- throws the error -->
{{profileUser.name.firstName}}
</pre>

仅供参考,profileUser如下所示:

FYI, the profileUser looks like this:

{
  "id": "9830ecfa-34ef-4aa4-86d5-cabbb7f007b3",
  "name": {
    "firstName": "John",
    "lastName": "Doe",
    "fullName": "John Doe"
  }
}

如果有人可以帮助我,那会很棒,这真的让我回过头来熟悉Angular v2。谢谢!

Would be great if somebody could help me out, this is really holding me back to get familiar with Angular v2. Thanks!

推荐答案

实际上你的 profileUser 对象是从HTTP加载的请求,它可以在开头 null json 管道只执行 JSON.stringify

In fact your profileUser object is loaded from an HTTP request and it can be null at the beginning. The json pipe simply does a JSON.stringify.

这是您的错误消息所说的: undefined不是对象(评估'l_profileUser0.name')

It's what your error message said: undefined is not an object (evaluating 'l_profileUser0.name').

您需要确保 profileUser 对象不为null才能获取其 name 属性等等。这可以使用 * ngIf 指令来完成:

You need to be sure that your profileUser object isn't null to be able to get its name attribute and so on. This can be done using an *ngIf directive:

<div *ngIf="profileUser">
  {{profileUser.name | json}}
</div>

当数据存在时,将显示HTML块。

When the data will be there, the HTML block will be displayed.

Eric 表示,Elvis运营商也可以为您提供帮助。而不是 {{profileUser.name | json}} ,您可以使用 {{profileUser?.name | json}}

As Eric stated the Elvis operator could also help you. Instead of having {{profileUser.name | json}}, you could use {{profileUser?.name | json}}.

希望它可以帮到你,
Thierry

Hope it helps you, Thierry

这篇关于Angular 2:{{object}}起作用,{{object.child}}抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆