En tant que débutant, je suis confronté à un problème avec Angular et Observables. J'ai une API pour obtenir des informations sur un restaurant spécifique dans la base de données, mais je dois l'obtenir avec une demande POST. J'ai réussi à obtenir restaurantID à partir d'auth.service et d'une autre API lorsque le restaurant est connecté, mais lorsque j'ai essayé de connecter le restaurant dans la console, j'obtiens indéfini . De manière uniforme, je n'ai pas l'autorisation d'afficher l'API ici. Le code:
restaurant.service.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../services/auth.service';
import { RestaurantService } from '../services/restaurant.service';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
import { Observable } from 'rxjs';
@Component({
selector: 'app-informacije',
templateUrl: './informacije.component.html',
styleUrls: ['./informacije.component.scss']
})
export class InformacijeComponent implements OnInit {
restaurant: Restaurant;
loggedRestaurant: LoggedRestaurant;
restaurantID;
constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }
getRestaurant() {
return this.restaurantService.getRestaurant()
}
ngOnInit() {
this.restaurant = this.authService.currRestaurant[0];
console.log(this.restaurant)
console.log(this.loggedRestaurant)
this.restaurantID = this.restaurant.id;
console.log(this.restaurantID)
this.restaurantService.restaurantID =this.restaurantID;
}
}
informacije.component.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Restaurant } from '../models/Restaurant';
import { LoggedRestaurant } from '../models/LoggedRestaurant';
@Injectable({
providedIn: 'root'
})
export class RestaurantService {
private restaurantUrl = 'xxxxxxxxxxxx';
public restaurant: Restaurant;
public loggedRestaurant: LoggedRestaurant
public restaurantID;
constructor(private http: HttpClient) { }
public getRestaurant(): Observable<LoggedRestaurant> {
return this.http.post<LoggedRestaurant>(this.restaurantUrl, this.restaurantID);
}
}
3 Réponses :
httpClient.post () renvoie un observable (RXJS). Vous devez donc vous y abonner. Sinon, vous pouvez utiliser le async pipe .
dans votre html, vous pouvez essayer ceci ,
<span *ngIf="data">{{data}}</span>
OU ,
vous pouvez déclarer une variable dans vos ts comme data , et,
this.restaurantService.getRestaurant().subscribe(payload => {
this.data = payload;
})
et dans votre html, vous pouvez ajouter,
<span>{{getRestaurant() | aync}}</span>
Merci pour votre temps, mais j'ai déjà essayé `` `` getRestaurant () {return this.restaurantService.getRestaurant (). Subscribe (data => {this.loggedRestaurant = data})} `` mais il renvoie toujours indéfini
Vous retournez toujours un observable. Faites exactement ce que je suggère.
Je l'ai fait aussi, désolé si je vous envoie cette question.
Vous devez vous abonner à votre appel API.
Dans informacije.component.ts
getRestaurant() {
return this.restaurantService.getRestaurant()
.subscribe(data => this.restaurant = data);
}
Cela attribuera la valeur renvoyée par votre service à votre champ restaurant de manière asynchrone.
Dans ngOnInit () , appelez getRestaurant comme suit
async ngOnInit() {
let restaurant = await this.getRestaurant().toPromise();
...
}
Les observables doivent être abonné pour pouvoir faire une demande, et ils sont asynchrones, ce qui signifie que même lorsque vous y êtes abonné, vous n'aurez pas les bons journaux. Avant d'utiliser une bibliothèque, je vous suggère vivement de lire la documentation : nous sommes là pour vous aider en cas de problèmes, mais ce n'est pas un problème, c'est juste que vous n'apprenez pas les bases du framework que vous êtes sur le point d'utiliser (sans infraction)
Vous n'appelez jamais votre fonction
getRestaurant ()dansInformacijeComponent.@trichetriche, vous avez raison, je dois en savoir plus sur les rxjs, je sais. uniformément, mais je fais travailler ce projet en même temps que j'apprends angular. Merci pour votre temps :)