Yardi
Yardi

Reputation: 473

Simple reading async api request in angular app not working

I just want to read data from my api, but I can't get to the structure, only observable or promise. My service:

@Injectable({
  providedIn: 'root'
})
export class AttractionService {

  constructor(private http: HttpClient) { }

  async getAtttractions(): Promise<Observable<any>> {
    return this.http.get<any>("https://localhost:7273/api/Attraction/Attractions");
  }
}

And my call in my component in ngOnInit:

constructor(private attractionService: AttractionService) { }

  async ngOnInit(){
    let y;
    await this.attractionService.getAtttractions()
      .then(x => {
        y = x;
      })
    console.log(y);
  }

Currently I getting in console.log this:

Observable {source: Observable, operator: ƒ}

How to get my structure (api call is working fine).

Upvotes: 0

Views: 83

Answers (2)

Mark B.
Mark B.

Reputation: 1

The Angular http library uses Observables, which is a different pattern than promises/await. Your code should be:

this.attractionService.getAttractions()
    .subscribe(x => {
        y = x;
        console.log(y);
    });

EDIT:

If you absolutely need to await, then convert the observable to a promise:

await firstValueFrom(this.attractionService.getAttractions());

Edit 2:

Your code inside the attractionService does not need to return a promise at all. It should return the Observable, not the promise of an Observable. Angular http services does not use promises at all unless you force it to by converting the Observable to a promise.

Upvotes: 0

Yardi
Yardi

Reputation: 473

I make it maybe more simpler to understand what I want:

async ngOnInit(){
    let thereIWantData;
    await this.attractionService.getAtttractions()
      .then(thereNot1 => {
        console.log("Data from promise")
        console.log(thereNot1);
        thereNot1.pipe(first()).subscribe(thereNot2 => {
          thereIWantData = thereNot2
          console.log("Data from observable")
          console.log(thereNot2);
        })
      })
    console.log("There i want data from observable")
    console.log(thereIWantData);
  }

And my logs:

Data from promise
Observable {source: Observable, operator: ƒ}
There i want data from observable
undefined
Data from observable
[{…}]

I want to get [ {...} ] instead of undefined

Upvotes: 0

Related Questions