如何让当前用户跨越angular2 / 4中的所有组件

时间:2017-05-05 12:42:42

标签: angular

我需要在不同组件的整个应用中使用此current_user。这是服务工作吗?

我该怎么做?以这种方式使用Service感觉不对。

import { Injectable, OnInit } from '@angular/core';
import { Headers, Http } from '@angular/http';
import { User } from './user';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class UserService implements OnInit {

  private host = 'http://localhost:3000';
  private userUrl = 'api/user';

  currentUser: User;

  constructor(private http: Http) { }

  ngOnInit() {
    this.getUser().then( user => this.currentUser = user);
  }

  getUser() : Promise<User> {
    const url = `${this.host}/${this.userUrl}`;
    return this.http.get(url)
      .toPromise()
      .then(res => res.json().data as User)
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

}

在其他组成部分:

  currentUser: User;

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.currentUser = this.userService.currentUser;
    console.log(this.currentUser);
  }

0 个答案:

没有答案