我有一个名为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