2015-12-24 31 views
7

Đã làm việc với Angular v1 trong một thời gian và kể từ khi Angular v2 đến Beta, được chơi xung quanh với điều đó.Góc 2: {{object}} hoạt động, {{object.child}} ném lỗi

Bây giờ tôi đã có đoạn mã này, nhưng không thể làm cho nó hoạt động, thực sự không biết tại sao. Bằng cách nào đó, khi tôi in {{profileUser | json}} mọi thứ hoạt động tốt (profileUser là một đối tượng).

Nhưng khi tôi muốn in một đứa trẻ của đối tượng đó (ví dụ {{profileUser.name}} hoặc {{profileUser.name.firstName}}), góc ném các lỗi sau:

EXEPTION: TypeError: undefined is not an object (evaluating 'l_profileUser0.name') in [ {{profileUser.name}} in [email protected]:11.

Nó thực sự khó hiểu với tôi, nên chỉ là một trong những điều đơn giản nhất xung quanh .. Chỉ cần bắt đầu với nguyên cảo btw ..

Dưới đây là một số mã - 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); 
      } 
     ) 
     ; 
    }); 
    } 
} 

Và đây là của tôi 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); 
     }) 
    ; 
    } 
} 

Cuối cùng, profile.html mẫu:

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

hoặc ..

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

hoặc ..

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

FYI, các profileUser trông như thế này:

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

Sẽ là tuyệt vời nếu ai đó có thể giúp tôi ra, điều này thực sự khiến tôi trở lại làm quen với Angular v2. Cảm ơn!

+2

[Elvis điều hành] (https : //angular.io/docs/ts/latest/guide/template-syntax.html) –

+0

tại sao bạn gói nó trong một lời hứa btw? – foxx

+0

Tôi đã không ở lúc đầu, đoán bạn thử bất cứ điều gì ;-) –

Trả lời

21

Thực tế, đối tượng profileUser của bạn được tải từ yêu cầu HTTP và có thể là null ngay từ đầu. Ống json chỉ đơn giản là JSON.stringify.

Đó là thông báo lỗi của bạn cho biết: undefined is not an object (evaluating 'l_profileUser0.name').

Bạn cần đảm bảo rằng đối tượng profileUser của bạn không phải là rỗng để có thể nhận thuộc tính name và cứ như vậy. Điều này có thể được thực hiện bằng cách sử dụng chỉ thị *ngIf:

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

Khi dữ liệu sẽ ở đó, khối HTML sẽ được hiển thị.

Eric tuyên bố nhà điều hành Elvis cũng có thể giúp bạn. Thay vì có {{profileUser.name | json}}, bạn có thể sử dụng {{profileUser?.name | json}}.

Hy vọng nó giúp bạn, Thierry

+0

Cảm ơn rất nhiều! Điều đó đã làm được. Nhưng điều này mới trong v2? Chúng ta có nên làm điều này mọi lúc không? –

+1

Trong thực tế, Angular1, điều này được thực hiện hoàn toàn. Bạn không có lỗi và không có gì được hiển thị. Thảo luận về [vấn đề] này (https://github.com/angular/angular/issues/791) có thể khiến bạn quan tâm ;-) –

3

Nó xảy ra bởi vì khi điều khiển của bạn được tạo ra, các profileUser là undefined. Và, khi bạn sử dụng {{profileUser | json}} bộ lọc json biết rằng dữ liệu của bạn không được xác định và không làm gì cả.Khi số profileUser cuối cùng được xác định, các cập nhật góc sẽ cắt toàn bộ điều và sau đó profileUser | json hoạt động. Tuy nhiên, khi bạn sử dụng {{ profileUser.anything | json}} bạn sẽ gặp lỗi vì hồ sơ Người dùng bắt đầu undefined.

Bạn có thể giải quyết nó, thiết lập một hồ sơ cá nhân có sản phẩm nào để biến của bạn ngay từ đầu của điều khiển của bạn, chỉ cần như thế:

profileUser = { name: {}}; 

Bằng cách này, profileUser sẽ không bao giờ undefined

Các vấn đề liên quan