我正在尝试构建自动完成,我正在使用Observable和Subject。但是只要Subject对象的值发生更改,就不会调用service方法。下面是我已经定义了主题的组件代码。
detailsPersist.component.ts
import { Component, OnInit } from "@angular/core";
import { Subject } from 'rxjs/Subject';
import { DataService } from './data.service';
export class DetailsPersistComponent implements OnInit{
products;
term = new Subject();
constructor(private _dataService: DataService){
}
ngOnInit(){
this._dataService.getSwiftProducts(this.term)
.subscribe(products => this.products = products)
}
search($event) {
let q = $event.target.value
console.log(q)
this.term.next(q)
}
}
以下是我的数据服务的代码
data.service.ts
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs';
@Injectable()
export class DataService{
getSwiftProducts(term): Observable<any>{
return this._http.get("/api/getSwiftProduct/:"+term)
.map(result => this.result = result.json().data)
}
}
答案 0 :(得分:1)
你可能想做这样的事情:
ngOnInit() {
this.subscription = this.term
.switchMap(term => this._dataService.getSwiftProducts(term))
.subscribe(products => this.products = products)
}
ngOnDestroy() {
this.subscription.unsubscribe();
}