【问题标题】:AngularJS 2 observables http change detectionAngularJS 2 observables http 变化检测
【发布时间】:2017-07-03 23:55:53
【问题描述】:

很久没有做 Angular2 了,如果我没有正确理解 observables,请道歉......在我订阅的组件中,getData 位于服务类中。我想要的是当 url 发生变化时 http get 调用并将更改自动发送回调用者/订阅者(可能还有任何其他 URL 参数)。如何做到这一点?我可能没有正确理解 observables 吗?

@Injectable()
export class HttpService {

    url: string;

    constructor(
        private http: Http
    ) {}

    getData() {
        return this.http.get(`${this.url}`)
            .map((res:Response) => res.json());
    }

    setUrl(url) {
        this.url = url;
    }
}

【问题讨论】:

    标签: angular rxjs angular2-services rxjs5 angular2-http


    【解决方案1】:

    在您的实现中,getData() 使用this.url 在调用 getData() 时保持的任何值。换句话说,如果您在调用getData() 之后更改this.url,则不会发生任何事情。

    要按照您的描述进行操作,您需要将不同 URL 的流包装在 observable 中:

    import {Subject} from 'rxjs/Subject';
    
    @Injectable()
    export class HttpService {
      // The `url` property is replaced with an observable emitting a stream of URLs.
      private _urlsStream: Subject<string> = new Subject<string>();
    
      constructor(private http: Http) {}
    
      // The http.get() now gets its urls from the url stream.
      // Every time a new url is pushed to the stream, a new request is executed.
      getData() {
        return this._urlsStream.asObservable()
          .mergeMap((url: string) => this.http.get(url))
          .map((res: Response) => res.json());
      }
    
      setUrl(url) {
        // Setting an url pushes the given url to the stream.
        this._urlsStream.next(url);
      }
    }
    

    这段代码肯定比原始版本更复杂。我添加了 cmets 来澄清一下,但如果您是 RxJS 新手,我强烈建议您花一些时间 reading the manualwatching some tutorials

    你会想了解:

    • 不同类型的可观察对象(我使用了Subject,这是一种特殊类型的可观察对象,既可以发出值又可以被订阅)。
    • 不同类型的运算符(我使用mergeMap() 将一个可观察对象(URL 流)“投影”到另一个可观察对象(HTTP 请求)中。

    【讨论】:

      猜你喜欢
      • 2017-05-04
      • 1970-01-01
      • 2017-02-09
      • 2017-06-16
      • 2017-11-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      相关资源
      最近更新 更多