服务值更改时更新组件值Angular 8

时间:2019-11-20 15:17:16

标签: angular typescript observable

我有一个Angular 8项目,其中有两个同级组件,都使用一项服务来更新餐厅数据。本质上,我有一个组件显示从api抓取的餐馆列表,还有一个同级组件可以过滤第一个组件显示的餐馆。我正在使用一项服务来获取和设置餐厅列表,但是我的代码当前未填充任何正在加载的数据。这是我的组件和服务的代码

Resturant.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()
  }
}

我发现了许多与此相关的问题,但是没有一个解决方案对我有用。

1 个答案:

答案 0 :(得分:2)

您需要在http获得响应后通过BehaviorSubject发出值:

 Schema::create('projects', function (Blueprint $table) {
                    $table->bigIncrements('id');
                    $table->unsignedInteger('owner_id');
                    $table->string('title');
                    $table->text('description');
                    $table->timestamps();
                    $table->foreign('owner_id')->references('id')->on('users')->onDelete('cascade');
                    });
    Schema::create('users', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->string('name');
                $table->string('email')->unique();
                $table->timestamp('email_verified_at')->nullable();
                $table->string('password');
                $table->rememberToken();
                $table->timestamps();
            });