[英]Updating component values when service value changes Angular 8
我有一個 Angular 8 項目,其中包含兩個兄弟組件,它們都使用服務來更新餐廳數據。 從本質上講,我有一個組件顯示從 api 抓取的餐廳列表,還有一個兄弟組件可以過濾第一個組件顯示的餐廳。 我正在使用一項服務來獲取和設置餐廳列表,但我的代碼目前沒有填充任何加載數據。 這是我的組件和服務的代碼
餐廳服務.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 得到響應后,您需要通過 BehaviorSubject 發出值:
@Injectable()
export class EatstreetService {
radius;
address;
public restaurants: = new ReplaySubject(1);
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.httpClient.get(`https://api.com/publicapi/v1/restaurant/search`, {params})
.subscribe(resp => this.restaurants.next(resp) ) ;
}
public getRestaurant(): Observable<any>{
return this.restaurants.asObservable();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.