Angular - HttpClient: Map Get method object result to array property

后端 未结 5 605
忘了有多久
忘了有多久 2021-02-04 06:19

I am calling an API that returns a JSON Object. I need just the value of the array to map to a Observable . If I call api that just returns the array my service call works.

5条回答
  •  不思量自难忘°
    2021-02-04 06:51

    Thanks All, I was able to find solution by combining responses from @ Arun Redhu by providing a transfer object interface that the server sends back. Then solution provided by @CozyAzure by using the .map() to transform one Observable to the correct Observable Show[].

    Full Solution below for those interested.

    import {Observable} from 'rxjs/Observable';
    import {Contact} from '../models/show';
    import {environment} from '../../../environments/environment';
    // Use the new improved HttpClient over the Http
    // import {Http, Response} from '@angular/http'; 
    import {HttpClient} from '@angular/common/http';
    
    // Create a new transfer object to get data from server
    interface ServerData {
      shows: Show[];
    }
    
    @Injectable()
    export class ShowsService {
    
      constructor(private http: HttpClient ) { }
    
    // want Observable of Show[]
      findAllShows(): Observable {  
        // Request as transfer object 
        return this.http
          .get(`${apiURL}/shows`)
         // Map to the proper Observable I need 
          .map(res => res.shows); 
    
      }
    }
    

    All great now!!! Thanks . So depending on data returned I can either use directly or map to proper Observable I need.

提交回复
热议问题