Home > Net >  Why is Observable Subscribe Making My Class Empty
Why is Observable Subscribe Making My Class Empty

Time:03-01

I have created a service, when the service is called and do a console log of the parameter in the subscriber it shows my class empty. I have used Observable's in the past and I have never ran into this issue. If it serves me right the parameter can be any name. Code snippet below.

My service

export interface Products{
  _id: string,
  name: string
}


@Injectable({
  providedIn: 'root'
})
export class SearchService {

 
  constructor(private http:HttpClient) { }

  rootUrl = '/api'
  
   
  searchProducts(query:string) {
    console.log("Does it get  my  searchProducts");
    return this.http.post<{payload: Array<Products>}>(this.rootUrl   '/getProducts', {payload: query}, {
     
     headers: new HttpHeaders({'Content-Type': 'application.json'})       
    }).pipe(
       map(data => data.payload)
     
    );
        
  }

}

My Component.ts

sendData(event:any){

let query:string = event.target.value;

   this.searchService.searchProducts(query.trim()).subscribe(results =>{   
     console.log(results);  //results is a empty array
   });
 }

 

Can anyone tell me?

CodePudding user response:

Does your API response contain a field called payload? If so, does it have a value?

I recommend moving your console log up a level so that you can see what the API response is and what fields it has. Something like this,

searchProducts(query:string) {
  console.log("Does it get  my  searchProducts");
  return this.http.post<{payload: Array<Products>}>(this.rootUrl   '/getProducts', {payload: query}, {
 
   headers: new HttpHeaders({'Content-Type': 'application.json'})       
  }).pipe(
   map(data => {
     console.log('API Response => ', data);
     return data.payload
   })
 
);
    

}

CodePudding user response:

Add return before data.payload like this:

searchProducts(query:string) {
    console.log("Does it get  my  searchProducts");
    return this.http.post<{payload: Array<Products>}>(this.rootUrl   '/getProducts', {payload: query}, {
     
     headers: new HttpHeaders({'Content-Type': 'application.json'})       
    }).pipe(
       map(data => return data.payload)
     
    );
        
  }

If still doesn't work then it may be blank because of how you treat the request data. You're saying that the post will receive data in this format:

{payload: Array<Products>}

An object with a parameter with an array of products, and may not match the real data format coming from the API.

If you know that it will be an array then change for <Products[]> and if you know that will be an object with an array inside try <{Products[]}> or <{payload: Products[]}>, if don't work try to remove the <> and everything inside.

And the same applies to how you send the request body if the API doesn't receive in {payload: String} format then doesn't do what you asking for.

  • Related