【发布时间】:2019-11-20 23:41:35
【问题描述】:
我有一个 Angular 8 项目,其中包含两个同级组件,它们都使用服务来更新餐厅数据。本质上,我有一个组件显示从 api 抓取的餐馆列表,还有一个兄弟组件可以过滤第一个组件显示的餐馆。我正在使用一项服务来获取和设置餐厅列表,但我的代码目前没有填充任何加载数据。这是我的组件和服务的代码
餐厅.service.ts
@Injectable()
export class EatstreetService {
radius;
address;
public restaurants: BehaviorSubject<any> = new BehaviorSubject<any>(null);
constructor(private httpClient: HttpClient) { }
public setRestaurant(){
let params = new HttpParams();
params = params.append('method', 'delivery');
params = params.append('pickup-radius', this.radius);
params = params.append('street-address', this.address);
params = params.append('access-token', this.token)
this.restaurants.next(this.httpClient.get(`https://api.com/publicapi/v1/restaurant/search`, {params}))
}
public getRestaurant(): Observable<any>{
return this.restaurants.asObservable();
}
}
ResturantsFilter.component.ts
export class LocationComponent implements OnInit {
restaurants;
radius;
address;
constructor(private eatstreetService: EatstreetService) { }
setRestaurants() {
this.eatstreetService.setRestaurant()
}
getRestaurants() {
this.eatstreetService.getRestaurant().subscribe((data) => {
console.log(data['restaurants']);
this.restaurants = data['restaurants'];
})
}
onSelect(): void {
this.setRestaurants()
}
ngOnInit() {
this.setRestaurants()
this.getRestaurants()
}
}
ResturantsList.component.ts
export class CardsComponent implements OnInit {
restaurants;
constructor(private eatstreetService: EatstreetService) { }
getRestaurants() {
this.eatstreetService.getRestaurant().subscribe((data) => {
console.log(data['restaurants']);
this.restaurants = data['restaurants'];
})
}
setRestaurants() {
this.eatstreetService.setRestaurant()
}
ngOnInit() {
this.getRestaurants()
}
}
我发现了很多与此相关的问题,但没有一个解决方案对我有用。
【问题讨论】:
-
http get 请求是否为您提供了您想要的数据?我的意思是,如果你把它放在一个console.log 中,在把它放在BehaviorSubject 之前,你会得到什么?
-
好的,很好。你真的需要服务中的 getRestaurant 方法来进行订阅吗?您可以在 ResturantsList 和 ResturantsFilter 中执行类似 this.eatstreetService.restaurants.subscribe(blabla...) 的操作,因为由于 BehaviorSubject 类型,它已经可以观察到
-
它返回一个 observable 但没有数据。但是,如果我不使 this.restaurants 成为可观察对象,它会在控制台记录所需的餐厅列表。
标签: angular typescript observable