[英]Angular 2 not updating object from service
我有一個Angular 2應用程序,其中包含服務和組件。
服務:
import { Injectable } from '@angular/core';
import { User } from '../dtos';
import { Http, Response } from '@angular/http';
@Injectable()
export class UserService {
public user: User;
constructor(private http: Http){}
public authenticate(username: string, email:string) {
var __this = this;
this.http.get('https://randomuser.me/api/')
.subscribe((response: Response) => {
__this.user = new User();
var respData = response.json();
var userResult = respData.results[0];
var seed = respData.info.seed;
__this.user.email = userResult.email;
__this.user.firstName = userResult.name.first;
__this.user.lastName = userResult.name.last;
__this.user.profilePicture = userResult.picure;
__this.user.id = seed;
})
}
}
組件:
import { Component } from '@angular/core';
import { User } from '../../dtos';
import { UserService } from '../../services';
@Component ({
selector: 'navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent{
user: User;
constructor(private userService: UserService){}
ngOnInit(){
this.user = this.userService.user;
}
}
和組件的html模板:
<ul class="topnav">
<li><a routerLinkActive="active" routerLink="/home">Home</a></li>
<li><a routerLinkActive="active" routerLink="/about">About</a></li>
<li class="right" ><a href="#">{{user.userName}}</a></li>
</ul>
當UserService.authenticate中的http.get調用返回有效的用戶對象時,我將使用數據更新本地用戶屬性。 導航欄組件不會注冊用戶對象已更新,並且永遠不會將數據放入模板中。
有什么想法如何使更新的用戶數據顯示在導航欄組件中?
您可以在下面嘗試,
用戶服務
export class UserService {
private _user: Subject<User> = new Subject<User>;
public get user() : string
{
return this._user;
}
constructor(private http: Http){}
public authenticate(username: string, email:string) {
var __this = this;
this.http.get('https://randomuser.me/api/')
.subscribe((response: Response) => {
let tempUser = new User();
var respData = response.json();
var userResult = respData.results[0];
var seed = respData.info.seed;
tempUser .email = userResult.email;
tempUser .firstName = userResult.name.first;
tempUser .lastName = userResult.name.last;
tempUser .profilePicture = userResult.picure;
tempUser .id = seed;
this.user.next(tempUser);
})
}
}
希望這可以幫助!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.