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

问题描述

使用 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';从'angular2/http'导入{标题};从 '../constants/constants' 导入 { API_PREFIX };从'angular2-jwt/angular2-jwt'导入{AuthHttp};导入 'rxjs/add/operator/map';@Injectable()导出类 ProfileService {API_PREFIX = API_PREFIX;构造函数(私有_authHttp:AuthHttp){}getProfileData(用户名:字符串):任何{返回新的承诺((解决,拒绝)=> {this._authHttp.get(API_PREFIX + '/users/username/' + 用户名).map(res => res.json()).订阅(数据 =>{解决(数据.数据);},错误 =>{拒绝(错误);});});}}

这是我的ProfileComponent:

import {Component, OnInit} from 'angular2/core';从'angular2/router'导入{RouteParams};从../../services/profile.service"导入{ProfileService};@成分({选择器:'个人资料',templateUrl: './components/profile/profile.html',指令:[],提供者:[ProfileService]})导出类 ProfileComponent 实现 OnInit {公共用户名:字符串;公开个人资料用户:任何;构造函数(私有_profileService:ProfileService,私人_params:RouteParams){this.username = this._params.get('username');}ngOnInit() {this.getProfileData(this.username);}getProfileData(用户名:字符串):无效{this._profileService.getProfileData(用户名).then(数据=> {this.profileUser = 数据;控制台日志(数据);});}}

最后,profile.html 模板:

<!-- 有效!-->{{个人资料用户 |json}}

或...

<!-- 抛出错误-->{{profileUser.name |json}}

或...

<!-- 抛出错误-->{{profileUser.name.firstName}}

仅供参考,profileUser 如下所示:

{"id": "9830ecfa-34ef-4aa4-86d5-cabbb7f007b3",姓名": {"firstName": "约翰","lastName": "母鹿",全名":约翰·多伊"}}

如果有人能帮助我就好了,这真的阻碍了我熟悉 Angular v2.谢谢!

解决方案

事实上,你的 profileUser 对象是从 HTTP 请求中加载的,它的开头可以是 null.json 管道只是做了一个 JSON.stringify.

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

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

{{profileUser.name |json}}

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

正如 Eric 所说,Elvis 接线员也可以为您提供帮助.而不是 {{profileUser.name |json}},你可以使用 {{profileUser?.name |json}}.

希望对你有帮助蒂埃里

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

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).

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 is not an object (evaluating 'l_profileUser0.name') in [ {{profileUser.name}} in ProfileComponent@4:11.

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

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);
          }
        )
      ;
    });
  }
}

And here is my 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);
      })
    ;
  }
}

Finally, the profile.html template:

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

or..

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

or..

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

FYI, the profileUser looks like this:

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

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

解决方案

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.

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

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>

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

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

Hope it helps you,Thierry

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

09-09 14:17