1
bbb(){
    return new Promise((resolve, reject) => {
      this.http.get(this.url).subscribe(data => {
          resolve(data)
        },
         error => {
          reject(error);
        },
      );
    });
  }

ngAfterContentInit(){
    console.log(//THIS LINE
      this.bbb().then(son => {
      return son;
    }));
  }

-This line- return ZoneAwarePromise in console. How can i return son's value?

OSentrk
  • 58
  • 1
  • 1
  • 9

1 Answers1

5

Better practise is to use Observable:

import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

bbb() {
 return this.http.get(this.url)
   .pipe(
     catchError(err => {
       console.log('err', err);
       return throwError('Something bad happened; please try again later.');
     });
}

And, then simply just subscribe to bbb:

import { Subscription } from 'rxjs';

testSubscription: Subscription;

ngAfterContentInit() {
    this.testSubscription = this.bbb()
      .subscribe(son => {
        console.log('son', son); // here you get the result
      });
}

Don't forget to unsubscribe:

ngOnDestroy() {
  this.testSubscription.unsubscribe();
}

If you still want to use Promise:

bbb() {
  return this.http.get(this.url).toPromise();
}

To get the result of bbb:

ngAfterContentInit() {
   this.bbb()
     .then(son => {
       console.log('son', son); // here you get the result
     })
     .catch(err => {
       console.log(err);
     });
}
Vadi
  • 3,279
  • 2
  • 13
  • 30
  • Can i reach son variable in any function? Because i have to create map icon on googlemaps. – OSentrk Jun 07 '19 at 22:04
  • You'll get `son` asyncroniously (after some time)...so if you want to use it in some function, call that function after you'll get the result (inside of `subscription` callback or `than`) – Vadi Jun 07 '19 at 22:08
  • Good that you're mentioning the observable way, but (1) `catchError` has to return an Observable and (2) the `$` suffix is usually only used for Observables but not Subscriptions. – frido Jun 07 '19 at 23:34
  • @fridoo good notice! corrected that part – Vadi Jun 07 '19 at 23:46