【问题标题】:Angular returns undefined角度返回未定义
【发布时间】:2019-10-09 16:19:20
【问题描述】:

我有用于获取数据库中一家特定餐厅信息的 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';

import { AuthService } from './auth.service'

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

  private restaurantUrl = 'https://dm.dnevnimeni.com/dmnew/podacirestorana.php';

  public restaurant: Restaurant;
  public loggedRestaurant: LoggedRestaurant
  public restaurantID = this.authService.currRestaurant[0].id

  constructor(private http: HttpClient, private authService: AuthService) { }

  getRestaurant(ID): Observable<LoggedRestaurant> {

    console.log('ID je' + this.restaurantID);

    return this.http.post<LoggedRestaurant>(this.restaurantUrl, ID);
  }

}

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 = this.authService.currRestaurant[0].id;;

  constructor(private restaurantService: RestaurantService, private authService: AuthService ) { }

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

  }

  ngOnInit() {

    this.getRestaurant();

    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;

  }
}


【问题讨论】:

  • 可能是您调用 REST 服务时输入无效。使用 CURL 或 POSTMAN 等方法确保 rest 服务按照您期望的方式工作。
  • 未定义的行从何而来?
  • 您不会在任何地方呼叫getRestaurant,因此不会请求服务呼叫。
  • loggedRestaurantsubscribe 回调中分配。调用ngOnInit时可能不可用
  • 我明白了。无论如何,您应该遵循@TonyNgo 的回答。我相信他的代码解决了您想要实现的目标,即通过订阅它来返回可观察值

标签: javascript angular typescript rxjs angular8


【解决方案1】:

更新 你的代码应该是这样的

由于您只需要获取数据,因此不必使用 post

所以你可以从这里改变

return this.http.post<LoggedRestaurant>(this.restaurantUrl, this.restaurantID);

到这里

return this.http.get<LoggedRestaurant>(`${this.restaurantUrl}/${this.restaurantID}`);

并添加 ngOnInit

ngOnInit() {
this.restaurantService.getRestaurant().subscribe(data  => {
   this.loggedRestaurant = data;
   // do something else
});

因为您的 getRestaurant() 方法没有在 ngOnInit 生命周期挂钩中调用,所以数据不可用

【讨论】:

  • 谢谢你的回答,但是当我尝试它时,控制台说ERROR TypeError: Cannot read property 'length' of undefined
  • 请更新屏幕截图,如果我不知道错误来自哪里,我帮不了你
  • @seven 再次检查我的答案
  • 哦,对不起。完成
  • 不,我试过了,也试过在nfOnInit()的开头调用getRestaurant(),但仍然得到undefined并且控制台抛出错误,我之前在屏幕截图中发布了错误评论
【解决方案2】:

您的代码存在一些问题。首先,您从未真正调用过getRestaurant() 函数,因此永远不会请求服务调用。

其次,您正在处理异步代码,不能指望在运行 console.log(this.loggedRestaurant) 之前完成服务调用。

我的建议是您将函数更改为返回 Observable&lt;LoggedRestaurant&gt; 并订阅它。

getRestaurant(): Observable<LoggedRestaurant> {
     this.restaurantService.getRestaurant().subscribe(data  => {
      this.loggedRestaurant = data;
    });
}

那么你就可以把它当做

ngOnInit() {
    this.getRestaurant().subscribe(loggedRestaurant => {
        console.log(loggedRestaurant);
    }); 
}

【讨论】:

    【解决方案3】:

    试试这个:

    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() {
         this.restaurantService.getRestaurant().subscribe(data  => {
          this.loggedRestaurant = data;
        });
    
      }
    
      ngOnInit() {
        this.getRestaurant(); // add this line
        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;
    
      }
    }
    

    【讨论】:

    • 当我尝试它时,控制台仍然返回undefined 加上控制台说link
    • getRestaurant() 方法中是否获取数据。
    • 不,从组件中的getRestaurant(),我得到undefined,从服务中的getRestaurant(),我得到Observable
    猜你喜欢
    • 2016-03-20
    • 2021-10-01
    • 1970-01-01
    • 2020-12-18
    • 2014-09-12
    • 2019-07-06
    • 2016-03-11
    • 2020-09-02
    • 1970-01-01
    相关资源
    最近更新 更多