Đã 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!
[Elvis điều hành] (https : //angular.io/docs/ts/latest/guide/template-syntax.html) –
tại sao bạn gói nó trong một lời hứa btw? – foxx
Tôi đã không ở lúc đầu, đoán bạn thử bất cứ điều gì ;-) –