【发布时间】: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,因此不会请求服务呼叫。 -
loggedRestaurant在subscribe回调中分配。调用ngOnInit时可能不可用 -
我明白了。无论如何,您应该遵循@TonyNgo 的回答。我相信他的代码解决了您想要实现的目标,即通过订阅它来返回可观察值
标签: javascript angular typescript rxjs angular8