What happens is that http.get
is a call asynchronous, that is, it is not guaranteed that it will return the results immediately, and the return
may even execute before the get
break up. http.get
returns a Observable
, whose method subscribe
serves to indicate what to do when something is returned. So in your code:
this.carService.getModel(modelId).subscribe(
data => modelName = data['name']);
return modelName;
The function that is within the subscribe
(the code data => modelName = data['name']
, which uses the syntax of Arrow Function) is a callback: she doesn’t perform immediately. You’re just saying: when the http.get
return something, execute it.
Only the HTTP call may take time, and the return
can be executed before the callback. That is, you may end up returning the modelName
before it is set.
But it was not clear why you need to return this information. Why not use it directly within the callback? Ex:
this.carService.getModel(modelId).subscribe(
data => {
// use o data['name'] diretamente aqui dentro
}
);
Or, if you only need name
, you can use the operations pipe
and map
, to turn the return into another Observable
:
import { map } from 'rxjs/operators';
getModel(modelId: number): Observable<string> {
return this.carService.getModel(modelId).pipe(
map(data => data['name'])
);
}
Thus, getModel
now returns a Observable<string>
, that is, containing only the value of data['name']
(I’m assuming that data['name']
is a string; if not, change the return type of the Observable
). The return must remain one Observable
, for the call that gives rise to everything (http.get
) is asynchronous, so if we try to return directly data['name']
, we fell into the same problem as the original code.
Then you use getModel
where necessary, remembering that now the return is the name
(and no longer the object data
):
this.getModel(1).subscribe(name => {
// usar o name do jeito que quiser
});
I think you missed the whole context of what you need, because I didn’t understand why you use the service within a function. Where you call the function
getModel(modelId: number)
?? Apparently this function is redundant.– LeAndrade