Angular2服务和良好实践

时间:2017-03-15 10:54:40

标签: angular service

我对angular2世界相当陌生,我正在寻找做某事的最佳方法。

其中之一是:查询Http端点的服务的最佳初始值是什么?

请考虑以下代码:

import { Injectable } from '@angular/core'
import { Observable } from 'rxjs/Observable'
import { BehaviorSubject } from 'rxjs/BehaviorSubject'

@Injectable()
export class CounterService {
    private _counter : BehaviorSubject<Number> = new BehaviorSubject(0)
    public counter : Observable<Number> = this._counter.asObservable()

    constructor () {
        this._counter.next(0)
    }

    public addOne () {
        this._counter.next(this._counter.getValue() + 1)
    }
}

我可以使用如下:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Counter value is {{sCounter.counter | async}}</h2>
      <button (click)="increment()">add one</button>
    </div>
  `,
})
export class App {
  constructor(private sCounter : CounterService) {
  }

  increment () {
   this.sCounter.addOne() 
  }
}

(c.f。this plunker

但很明显,有些服务会查询API以获取数据,而我不确定如何处理这些数据。

BehaviorSubject需要提供给订阅者的初始值(这很棒),但由于服务在您询问之前不会查询任何内容,因此其初始值赢得了&# 39;这是预期的,可能会打破用户界面。

示例:

    import { Injectable } from '@angular/core'
    import { Observable } from 'rxjs/Observable'
    import { BehaviorSubject } from 'rxjs/BehaviorSubject'

    @Injectable()
    export class UserService {
        private _user : BehaviorSubject<User> = new BehaviorSubject({} as User)
        public user : Observable<User> = this._user.asObservable()

        constructor (http: Http) {}

        public fetchUser(id) {
            this.http.get(`/user/${id}`).subscribe((user) => { this._user.next(user) })
        }
    }

正如您所看到的,当我第一次订阅此服务时,我将收到{}(代理用户)而不是真实用户,这可能会导致问题。

对此有什么好的模式吗?

1 个答案:

答案 0 :(得分:0)

我刚刚添加了一个.filter来获取我想要的值,它就可以了。 :)

import { Injectable } from '@angular/core'
import { Observable } from 'rxjs/Observable'
import { BehaviorSubject } from 'rxjs/BehaviorSubject'

@Injectable()
export class UserService {
    private _user : BehaviorSubject<User> = new BehaviorSubject({} as User)
    public user : Observable<User> = this._user.asObservable()
                                     .filter(user => user instanceof User)

    constructor (http: Http) {}

    public fetchUser(id) {
        this.http.get(`/user/${id}`).subscribe((user) => { this._user.next(user) })
    }
}