Как сделать асинхронные запросы от разных сервисов [Angular] - PullRequest
0 голосов
/ 23 марта 2019

У меня есть 3 сервиса с похожими методами, которые возвращают данные из базы данных. Я использую их в своем компоненте и хочу хранить каждый ответ данных в соответствующих компонентный массив. Как получить остальную часть данных от других служб? Я не очень знаком с forkjoin и т. Д. Было бы неплохо, если бы вы привели пример.

Services:

export class BrandService {
  private url: string;
  constructor(private http: HttpClient) {
    this.url = 'http://localhost:3000/brands';
  }

  public getJsonBrands(): Observable<any> {
    return this.http.get(this.url);
  }
}
__________________________________________
export class ProductService {
  private url: string;
  constructor(private http: HttpClient) {
    this.url = 'http://localhost:3000/products';
  }

  public getJsonProducts(): Observable<any> {
    return this.http.get(this.url);
  }
}
__________________________________________
export class CategoryService {
  private url: string;
  constructor(private http: HttpClient) {
    this.url = 'http://localhost:3000/categories';
  }

  public getJsonCategories(): Observable<any> {
    return this.http.get(this.url);
  }
}


Component: 

export class ProductsComponent implements OnInit {
  productList: Array<any>;
  brandList: Array<any>;
  categoryList: Array<any>;

  constructor(private productService: ProductService, private brandService: BrandService, private categoryService: CategoryService) {
   this.productService.getJsonProducts().subscribe(
     product => {
       this.productList = product;
     })

  ngOnInit() {

  }
}

_______________________________________
Code below doesnt seem to work, i keep getting console error "this.brandService.getJsonBrands is not a function"

ngOnInit() {
    forkJoin(
      this.productService.getJsonProducts(),
      this.brandService.getJsonBrands(),
      this.categoryService.getJsonCategories()
    )
      .subscribe(([res1, res2, res3]) => {
          this.productList = res1;
          this.brandList = res2;
          this.productList = res3;
          console.log(this.productList, this.brandList, this.productList);
      },
        error1 => {
          console.log(error1);
        });
  }

Ответы [ 3 ]

0 голосов
/ 23 марта 2019

Используйте ForkJoin или CombineLastest от Rxjs, разница между двумя объяснена здесь: Rxjs: Observable.combineLatest против Observable.forkJoin

ngOnInit() {
forkJoin(
      this.productService.getJsonProducts(),
      this.brandService.getJsonBrands(),
      this.categoryService.getJsonCategories() 
    )
    .subscribe(([res1, res2, res3]) => {
      this.productList = res1;
      this.brandList = res2;
      this.categoryList = res3;
    });
}
0 голосов
/ 23 марта 2019

Вы можете использовать combineLatest или forkJoin.Использование довольно похоже.Но вы должны отписаться от combineLatest, в отличие от forkJoin.

import { Subscription, combineLatest } from 'rxjs';

sub: Subscription;
myData: any;

ngOnInit() {
  this.sub = combineLatest(
    this.brandService.getJsonBrands,
    this.productService.getJsonProducts,
    this.categoryService.getJsonCategories
  ).subscribe(([brands, products, categories]) => {
    this.myData = {brands, products, categories};
    console.log('this.myData', this.myData);
  });
}

ngOnDestroy() {
    this.sub.unsubscribe();
}

forkJoin - Когда все наблюдаемые завершены, выведите последнее излученное значение из каждого.

CombinLatest - Когда какое-либо наблюдаемое излучает значение, испускает самое последнее значение из каждого.

0 голосов
/ 23 марта 2019

Вы должны подписаться на другую услугу, такую ​​как услуга продукта, и включить их в провайдеры

    constructor(private productService: ProductService,
                private brandService: BrandService,
                private categoryService: CategoryService) {
        this.productService.getJsonProducts().subscribe(product => {
          this.productList = product;
        })
        this.brandService.getJsonBrands().subscribe(brands=> {
           this.brandList = brands;
        })
        this.CategoryService.getJsonCategories().subscribe(categories=> {
           this.categoryList= categories;
        })
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...