2017-10-13 42 views
0

价值变化我试图建立一个自动完成,我使用Observable和主题。但是,只要Subject对象的值发生更改,服务方法就不会被调用。以下是我定义主题的组件代码。Observable不被称为Subject.next()

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) 
    } 
} 

回答

1

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

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

谢谢马丁。正是我需要的......只是编辑了你的答案,因为没有提到包含的软件包 – Apoorv