【问题标题】:Angular 2: {{object}} works, {{object.child}} throws errorAngular 2:{{object}} 有效,{{object.child}} 抛出错误
【发布时间】:2015-12-24 16:30:57
【问题描述】:

使用 Angular v1 已经有一段时间了,自从 Angular v2 进入 Beta 版以来,一直在玩这个。

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

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

EXEPTION: TypeError: undefined is not an object (evaluating 'l_profileUser0.name') in [ {{profileUser.name}} in ProfileComponent@4:11.

这真的让我很困惑,应该只是最简单的事情之一.. 顺便说一句,刚开始使用 TypeScript..

这是一些代码 - 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);
      })
    ;
  }
}

最后,profile.html 模板:

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

或者..

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

或者..

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

仅供参考,profileUser 如下所示:

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

如果有人可以帮助我,那就太好了,这确实阻碍了我熟悉 Angular v2。谢谢!

【问题讨论】:

  • 你为什么要把它包装在一个承诺中?
  • 一开始我没有,猜你什么都试;-)
  • @foxx 在 angular.io 文档中,他们正在使用承诺:angular.io/docs/ts/latest/tutorial/toh-pt4.html
  • 同意@foox,这里不需要promise,因为http.get返回一个可观察的对象(类似于promise但更强大的东西)。这个answer 可以帮助你。

标签: javascript angular angular2-services


【解决方案1】:

事实上,您的profileUser 对象是从HTTP 请求加载的,它可以在开头为nulljson 管道只执行 JSON.stringify

这是您的错误消息所说的:undefined is not an object (evaluating 'l_profileUser0.name')

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

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

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

正如Eric 所说,猫王接线员也可以帮助您。您可以使用{{profileUser?.name | json}},而不是{{profileUser.name | json}}

希望对你有帮助 蒂埃里

【讨论】:

  • 非常感谢!就是这样做的。但这是 v2 中的新功能吗?我们应该一直这样做吗?
  • 其实Angular1,这是隐式完成的。您没有错误,也没有显示任何内容。对此issue 的讨论可能会让您感兴趣;-)
【解决方案2】:

这是因为在创建控制器时,profileUser 未定义。而且,当您使用{{profileUser | json}} 时,过滤器json 知道您的数据未定义并且什么也不做。当 profileUser 最终被定义时,角度更新整个事情,然后 profileUser | json 工作。但是,当你使用{{ profileUser.anything | json}} 时,你会得到一个错误,因为profileUser 启动undefined

你可以解决它,在你的控制器开始时为你的变量设置一个空的配置文件,就像这样:

profileUser = { name: {}};

这样,profileUser 永远不会是undefined

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多