Angular Subject.next()中的值更改时未调用Observable

Angular Subject.next()中的值更改时未调用Observable,angular,rxjs,rxjs5,Angular,Rxjs,Rxjs5,我正在尝试建立一个自动完成,我正在使用可观察和主题。但是只要主题对象的值发生变化,就不会调用服务方法。下面是我定义主题的组件代码 detailsPersist.component.ts import { Component, OnInit } from "@angular/core"; import { Subject } from 'rxjs/Subject'; import { DataService } from './data.service'; export class Detail

我正在尝试建立一个自动完成,我正在使用可观察和主题。但是只要主题对象的值发生变化,就不会调用服务方法。下面是我定义主题的组件代码

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)
  }
}
从'@angular/core'导入{Injectable};
从'@angular/Http'导入{Http,Response,Headers,RequestOptions,URLSearchParams};
导入'rxjs/add/operator/map';
从“rxjs”导入{Observable};
@可注射()
导出类数据服务{
getSwiftProducts(术语):可观察{
返回此项。_http.get(“/api/getSwiftProduct/:”+术语)
.map(result=>this.result=result.json().data)
}
}

您可能希望执行以下操作:

ngOnInit() {
  this.subscription = this.term
    .switchMap(term => this._dataService.getSwiftProducts(term))
    .subscribe(products => this.products = products)
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}

您可能希望执行以下操作:

ngOnInit() {
  this.subscription = this.term
    .switchMap(term => this._dataService.getSwiftProducts(term))
    .subscribe(products => this.products = products)
}

ngOnDestroy() {
  this.subscription.unsubscribe();
}

谢谢你,马丁。正是我需要的。。。刚刚编辑了您的答案,因为没有提到要包含的包Hanks martin。正是我需要的。。。只是编辑了你的答案,因为没有提到要包含的包