Reputation: 196
In the earlier angular version, in our service, we could simply map the response to a JSON object as follow :
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { HttpClient } from '@angular/common/http';
@Injectable()
export class MakeService {
constructor(private http:HttpClient) { }
getMakes(){
return this.http.get('/api/myAPI')
.map(res=>res.json());
}
}
However, in angular 5 we don't have HTTP anymore and we have to use HttpClient instead, what should be added to the code above to work in angular5.
my component looks like :
makes : any[];
constructor(private makeservice: MakeService) { }
ngOnInit() {
this.makeservice.getMakes().subscribe(makes=>{
this.makes=makes;
console.log("MAKES",this.makes);
});
}
simply by removing the ":any[]" data type from make it will work, but I need to pass the JSON object to component from service.
Upvotes: 0
Views: 5173
Reputation: 9443
According here. You should always subscribe to any request made by httpclient
Always subscribe!
An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods.
const req = http.get<Heroes>('/api/heroes');
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.
Upvotes: 0
Reputation: 222532
Try the following,
getMakes(){
return this.http.get('/api/myAPI')
}
and in component,
constructor(public data:DMakeService ){
this.data.getMakes().subscribe(data=>{
console.log(data);
})
}
Upvotes: 3
Reputation: 13682
You don't need to map to JSON anymore, so this is sufficient:
getMakes(){
return this.http.get('/api/myAPI');
}
This returns an Observable, however, not a Promise, so you'd have to subscribe the return value to get the result. If you want to keep working with promises, you can do this:
getMakes(){
return this.http.get('/api/myAPI').toPromise();
}
Upvotes: 0