2016-09-22 81 views
0

我有一個角度爲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組件不會註冊用戶對象已更新,也不會將數據放入模板中。

任何想法如何讓更新的用戶數據顯示在導航欄組件?

+0

您應該使用Observable和異步管道:http://briantroncone.com/?p=623 – pietro909

+0

我還會補充說,將_user_作爲公共屬性公開是一種反模式,因爲它允許可變性。該服務沒有完全控制它。爲什麼你不使用getter/setter? – pietro909

回答

1

你可以嘗試以下,

UserService

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); 
     }) 
    } 
} 

希望這有助於!

+0

現在'UserService'給''User'的'Observable',你必須在模板中使用'async'管道。請參閱[AsyncPipe](https://angular.io/docs/ts/latest/guide/pipes.html#!#async-pipe) –