我有一個名爲ProfileComponent的組件,它使用名爲ProfileService的服務來檢索其數據。 ProfileService有一個名爲getProfile的方法,返回一個promise。在當時的方法中,我將必要的配置文件數據分配給稱爲配置文件的組件上的公共屬性。問題在於,該視圖似乎並未等待解決在視圖中顯示信息的承諾。這只是給出一個錯誤,「屬性未定義」。我看過使用Page life Cycle Hooks,但它沒有幫助解決問題。組件查看不顯示數據已解決的數據
成型件
import { Component , OnInit } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Profile } from './profile';
import { ProfileService } from './profile.service';
@Component({
selector:'profile',
templateUrl: 'build/profile/profile.component.html',
providers: [ProfileService]
})
export class ProfileComponent{
// public properties
profile: Profile;
constructor(private profileService: ProfileService){
this.getProfile();
}
private getProfile(){
this.profileService.getProfile()
.then(data => {
console.log(data); // I see the needed data here
this.profile = data;
});
}
}
檔案服務
imports...
@Injectable()
export class ProfileService {
profile: Profile = {
"firstName": 'Chelsea',
"lastName": 'Wilson',
"phone": '713-567-0957',
"email": '[email protected]',
"authorizationCode":'1232839475234537',
"agreementExpiration": new Date('12/31/2017'),
"ESIID" : '123294734SDFDSSD23'
};
getProfile(){
return Promise.resolve(this.profile);
}
}
資料查看
<div class="main-nav-wrapper">
<div class="main-nav-content brite-card">
<h2 class="brite-card-header">Personal Details</h2>
<div class="profile-item">
<span class="profile-label">Name</span>
<span class="profile-detail">{{profile.firstName}} {{profile.lastName}}</span>
</div>
<div class="profile-item">
<span class="profile-label">Email</span>
<span class="profile-detail">{{profile.email}}</span>
</div>
<div class="profile-item">
<span class="profile-label">Phone Number</span>
<span class="profile-detail">{{profile.phone}}</span>
</div>
<div class="profile-item">
<span class="profile-label">Authorization Code</span>
<span class="profile-detail">{{profile.authorizationCode}}</span>
</div>
<div class="profile-item">
<span class="profile-label">Agreement Expiration Date</span>
<span class="profile-detail">{{profile.agreementExpiration}}</span>
</div>
<div class="profile-item">
<span class="profile-label">ESIID</span>
<span class="profile-detail">{{profile.ESIID}}</span>
</div>
</div>
</div>
錯誤
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in build/profile/profile.component.html:5:41
ORIGINAL EXCEPTION: TypeError: Cannot read property 'firstName' of null
PS
我有其他組件和服務,一起工作,但我使用*ngFor
,以顯示其信息,所以我認爲*ngFor
正對的影響其他。
謝謝你。這是一個更優雅的解決方案。 – inspired
很高興我能幫忙:) – sebaferreras