Gargoyle
Gargoyle

Reputation: 10294

Angular subscribe to observable then return a new one

I'm using HttpClient to get data from a webservice. I want to subscribe to the resulting data and convert it from JSON into actual classes, and then have an Observable of those classes returned from the method. Basically when the caller's subscribe fires I want it to get the classes.

I'm pretty new to angular and observables, so I'm not sure how to do that chaining. So I'm wanting something like:

constructor(private http: HttpClient) {}

getExistingArsByLab(labId: number) : Observable<EhsAssessmentAr[]> {
    return this.http.get("...")
        .subscribe(json => json.map(obj => {
            let ar = new EhsAssessmentAr();
            ar.id = obj['id'];
            ...
            return ar;
    }));
}

which of course doesn't actually compile and then the caller would just do:

this.getExistingArsByLab(12).subscribe(ars => { ... });

and at that point I'd have ars as an actual EhsAssessmentAr[].

Upvotes: 2

Views: 2268

Answers (2)

Chau Tran
Chau Tran

Reputation: 5088

Combined with @Antoniosss answer, I think this should solve your problem:

getExistingArsByLab(labId: number) : Observable<EhsAssessmentAr[]> {
 return this.http.get("...")
    .pipe(map(obj =>  {
        return obj.map(element => {
           let ar = new EhsAssessmentAr();
           ar.id = element['id'];
           ...
           return ar;
        });
 }));
}

Note that map from Observable is different than Array.map()

Upvotes: 2

Antoniossss
Antoniossss

Reputation: 32507

Dont subscribe right away but pipe and map

getExistingArsByLab(labId: number) : Observable<EhsAssessmentAr[]> {
    return this.http.get("...")
        .pipe(map(obj =>  {
            let ar = new EhsAssessmentAr();
            ar.id = obj['id'];
            ...
            return ar;
    }));

}

You must fix brackets and add proper mapping.

Upvotes: -1

Related Questions