Chamada HTTP síncrona angular 5
Eu tenho um aplicativo Angular 5 no qual preciso chamar algum serviço REST pesado (geralmente leva alguns segundos). Preciso do resultado em diferentes partes do aplicativo, portanto, gostaria de armazenar o resultado em um DataStorageService. Basicamente, é isso que eu gostaria de alcançar:
@Injectable()
export class DataStorageService {
private result: MyCustomObject;
constructor(private service: Service) {}
getResult(): MyCustomObject {
if (typeof this.result === 'undefined') {
// save result
}
return result;
}
A questão é como posso esperar até que a solicitação HTTP seja concluída e salvar e retornar o objeto 'resultado'. Tentei resolvê-lo usando Promise e Observable também, mas nenhum deles funcionou bem.
Observável:
if (typeof this.result === 'undefined') {
this.service.call()
.subscribe(response => this.result = response);
}
return this.result; // wait for save and return MyCustomObject
Promessa:
if (typeof this.result === 'undefined') {
this.service.call()
.toPromise()
.then(response => this.result = response);
}
return this.result; // wait for save and return MyCustomObject