角度方法返回未定义

时间:2019-05-22 08:36:18

标签: javascript angular

作为一个初学者,我遇到了Angular和Observables的问题。我有API来获取有关数据库中某一特定餐厅的信息,但是我必须通过POST请求来获取它。餐馆登录后,我成功从auth.service和另一个API中获取了restaurantID,但是当我尝试在控制台中登录餐馆时,却得到了undefined。一致,我没有在此处显示API的权限。代码:

restaurant.service.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);
  }
}

informacije.component.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;

  }
}

3 个答案:

答案 0 :(得分:2)

httpClient.post()返回observable(RXJS)。因此,您需要订阅。否则,您可以使用async pipe

在您的html中,您可以尝试一下,

<span>{{getRestaurant() | aync}}</span>

OR

您可以在ts中声明一个变量,例如 data ,以及

this.restaurantService.getRestaurant().subscribe(payload => {
  this.data = payload;
})

,然后在您的html中添加

<span *ngIf="data">{{data}}</span>

答案 1 :(得分:0)

您需要订阅API调用。
informacije.component.ts

getRestaurant() {
    return this.restaurantService.getRestaurant()
    .subscribe(data => this.restaurant = data);
  }

这会将您的服务返回的值以异步方式分配给您的restaurant字段。

答案 2 :(得分:0)

ngOnInit()中按如下所示致电getRestaurant

async ngOnInit() {
  let restaurant = await this.getRestaurant().toPromise();
  ...
}