我有一個角度爲2的應用程序,帶有服務和組件。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調用與返回有效的用戶對象,我用數據更新本地用戶屬性。 Navbar組件不會註冊用戶對象已更新,也不會將數據放入模板中。
任何想法如何讓更新的用戶數據顯示在導航欄組件?
您應該使用Observable和異步管道:http://briantroncone.com/?p=623 – pietro909
我還會補充說,將_user_作爲公共屬性公開是一種反模式,因爲它允許可變性。該服務沒有完全控制它。爲什麼你不使用getter/setter? – pietro909