angularobservableangular2-services

Are observable lazy ? Angular 5


 this.postService.delete(ps).subscribe(resp => this.res = resp);
 console.log('result'+this.res);

console show result : undefined

does observable are lazy ?


Solution

  • It has nothing to do with lazyness. It has to do with asynchronism.

    You're sending an AJAX request. The first A in AJAX means asynchronous. This means that you send the request, and the execution doesn't block until the response comes back. That would freeze the whole application. And even if it did, you would then not have to deal with observables. HttpClient would simply return the response directly.

    So, instead, it's asynchronous: you send the request, and continue doing whatever you want while the request is being sent and handled by the server. When the response finally comes back (that can be several seconds later), the browser tells you it's available by invoking a callback function: the one you're passing to subscribe().

    You can see that as a toaster: you put your bread in the toaster, and you can keep reading your journal and browse Twitter while the bread is being toasted. You can't start eating your toast until the toaster tells you that the toast is ready.