Angular2在服务和组件之间同步

时间:2017-09-06 05:17:26

标签: json angular angular-services angular-components

我有一个" HomeComponent",它在用户界面中显示用户名。

使用服务从json文件中读取用户名。

我有AppComponent中提供的服务(HomeComponent的父级)并在HomeComponent中重用

AppComponent.html

<router-outlet></router-outlet>

AppComponent.ts

export class AppComponent {
constructor(private userService: UserService) {
    this.userService.fetchUserDetails();
}
}

UserService.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { User } from '../models/user';

import 'rxjs/add/operator/first';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class AppStateManagerService {
   private userDetails: User;

  private initializeUser(data) {
    this.userDetails = new User();
    this.userDetails.name = data.username;
    this.userDetails.id = data.userid;
   }
constructor(private http: HttpClient) {}

async fetchDeviceDetails() {
    let response = await this.http
        .get('./app/config/user.json')
        .first()
        .toPromise();
    this.initializeUser(response);
    return this.userDetails;
}

getUserDetails() {
    return this.userDetails;
}

}

HomeComponent.html

<div>{{user && user.name}}</div>

HomeComponent.ts

export class HomeComponent {
    user: User;

    constructor(private userService: userService) {
        this.user = this.userService.getUserDetails();
    }
}

我面临的问题是,在JSON解析完成之前,首先初始化HomeComponent,即在AppComponent中完成fetchUserDetails()之前,调用HomeComponent中的getUserDetails()并且user.name为null HTML,在填充服务之前。

有没有办法同步这个?不使用Observable?

2 个答案:

答案 0 :(得分:2)

fetchDeviceDetails()是异步的,所以我希望你能同意我getUserDetails()将立即返回undefined。简单的东西吧?

所以如何解决这个问题:你需要让HomeComponent知道数据是否可用。我们使用Observables来做到这一点。一个例子是:

fetchDeviceDetails(): Observable<any> {
  return new Observable(observer => {
    this.http.get(whatever).subscribe(
      res => {
        this.initializeUser(res);
        observer.next(res);
      }
    );    
  });
}

现在您可以订阅此活动:

constructor(private userService: userService) {
  this.userService.fetchDeviceDetails().subscribe(
    res => this.user = res
  );
}

答案 1 :(得分:1)

另一个选择是使用这样的getter:

export class HomeComponent {
    get user(): User {
       return this.userService.getUserDetails();
    }

    constructor(private userService: userService) {  }
}

这利用了Angular的变更检测,以确保用户数据一旦可用就在UI中设置。