Apoorv
Apoorv

Reputation: 620

Observable not being called on value change in Subject.next()

I am trying to build an autocomplete and I am using Observable and Subject. But the service method is not being called whenever the value of the Subject object changes. Below is my component code where I have defined the Subject.

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

Below is the code for my data service

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

Upvotes: 0

Views: 1011

Answers (1)

martin
martin

Reputation: 96899

You probably want to do something like this:

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

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

Upvotes: 2

Related Questions