0
我想知道如何執行一個http請求,在那裏我更新Angular2區域中的配置文件視圖。在我的頂層輪廓組件我目前做使用authHttp
一個簡單的HTTP請求:在Angular2中執行NgZone中的http請求
export class ProfileComponent implements OnInit {
constructor(
private auth: Auth,
private authHttp: AuthHttp) {}
ngOnInit() {
// update profile information
let headers: any = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
this.authHttp
.get('https://' + myConfig.domain + '/api/v2/users/' + this.auth.userProfile.user_id, {headers: headers})
.map(response => response.json())
.subscribe(
response => {
this.auth.userProfile = response;
localStorage.setItem('profile', JSON.stringify(response));
},
error => console.log(error.json().message)
);
}
}
的問題是,因爲該請求是異步的,個人資料頁面加載在此之前要求得到滿足和輪廓已更新。第一次點擊刷新時會發生什麼事什麼都沒有發生,因爲舊數據被加載到配置文件和新數據後。然後第二次刷新一切正常,因爲它只是使用從最後一次請求加載的新數據。
這個問題是否可以使用NgZone
解決?我能否以某種方式將此請求包含到區域中,以便完成後重新評估組件樹?
我對此仍有點困惑。什麼沒有更新?你的觀點?你是否綁定到視圖中的auth.userProfile?當通過authHttp的請求返回時它不會更新? – Steveadoo
@Steveadoo我將'auth.userProfile'中的某些數據作爲輸入傳遞到配置文件組件的模板中的另一個組件,因此它在作爲輸入傳遞舊數據之前可以更新'auth.userProfile' http請求 –
你怎麼知道這是一個區域問題?看着AuthHttp,它看起來不像是在角度區域之外運行。如果您將作爲@Input()屬性的auth.userProfile傳遞給其他組件,它應該在更改時自動更新。你碰巧正在讀這個其他組件中ngOnInit的@Input屬性嗎? – Steveadoo