Angular 2数据服务

时间:2016-07-29 23:51:47

标签: service angular observable

我正在根据以下文章构建可观察的数据服务:https://coryrylan.com/blog/angular-2-observable-data-services

在文章中他以数组为例,在这里我将使用用户对象,因为我正在开发用户服务。

这是我得到的:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Events, SqlStorage, Storage } from 'ionic-angular';
import { Subject } from 'rxjs/Subject';


export interface DataStore {
  user: Object
}

@Injectable()
export class UserService {

  private baseUrl: string;
  private storage: Storage;
  private _user$: Subject<Object>;
  private dataStore: DataStore;

  constructor(
    private http: Http
  ) {
    this.baseUrl = 'http://localhost:3000';
    this.storage = new Storage(SqlStorage);
    this._user$ = <Subject<Object>>new Subject();
    this.dataStore = {
      user: { name: '' }
    };
  }

  set user$(user: Object) {
    this.storage.set('user', JSON.stringify(user));
    this.dataStore.user = user;
    this._user$.next(this.dataStore.user);
  }

  get user$() {
    return this._user$.asObservable();
  }

  loadUser() {
    return this.storage.get('user').then(
      ((user: string): Object => {
        this.dataStore.user = JSON.parse(user);
        this._user$.next(this.dataStore.user);
        return this.dataStore.user;
      })
    );
  }

  login(accessToken: string) {
    return this.http
      .post('http://localhost:3000/login', { access_token: accessToken })
      .retry(2)
      .map((res: Response): any => res.json());
  }

  logout(): void {
    this.storage.remove('user');
  }

}

要进行身份验证,我调用login()函数并在一切正常时设置用户数据。

this.userService.login(this.data.accessToken)
  .subscribe(
    (user: Object) => {
      this.userService.user$ = user;
      this.nav.setRoot(EventListComponent);
    },
    (error: Object) => console.log(error)
  );

我觉得最好在服务中设置用户数据。我可以做到以下几点:

login(accessToken: string) {
  return this.http
    .post('http://localhost:3000/login', {
      access_token: accessToken
    })
    .retry(2)
    .map((res: Response): any => res.json())
    .subscribe(
      (user: Object) => {
        this.userService.user$ = user;
        this.nav.setRoot(EventListComponent);
      },
      (error: Object) => console.log(error)
    );
}

但我无法订阅组件中的login()函数,因为它已经订阅了。如果一切正常,如果组件出现问题但是将用户设置在服务中,我怎么能重定向用户呢?

在主要组件中,我加载用户数据并设置rootPage:

this.userService.loadUser().then(
  (user: Object) => this.rootPage = EventListComponent,
  (error: Object) => this.rootPage = LoginComponent
);

我认为此时调用loadUser()函数我不必再调用它,但我必须在需要用户数据的所有组件中调用它:

this.user = this.userService.user$;
this.userService.loadUser();

我认为服务不应该是这样,我能改进什么?有没有更好的方法来实现我想要的?任何例子或想法?

0 个答案:

没有答案