2017-10-13 44 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