【发布时间】:2019-05-22 16:47:43
【问题描述】:
作为初学者,我遇到了 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;
}
}
【问题讨论】:
-
Observables 需要订阅才能发出请求,并且它们是异步的,这意味着即使订阅了,您也不会拥有正确的日志。在使用库之前,我强烈建议您 read the documentation :我们会在出现问题时提供帮助,但这不是问题,只是您没有学习您将要使用的框架的基础知识(不进攻)
-
你永远不会在
InformacijeComponent中调用你的getRestaurant()函数。 -
@trichetriche,你说得对,我知道,我必须了解更多关于 rxjs 的知识。统一,但我让这个项目在我学习角度的同时进行。谢谢你的时间:)
标签: javascript angular