Тема вызова next () не видна в подписках на компоненты - PullRequest
0 голосов
/ 04 марта 2020

каждый раз, когда я пытаюсь подписаться на эту тему, это дает мне следующее

core. js: 6014 Ошибка: ошибка (в обещании): NullInjectorError: StaticInjectorError (AppModule) [HomeCompComponent -> PickStoreCompComponent]: StaticInjectorError (Платформа: ядро) [HomeCompComponent -> PickStoreCompComponent]: NullInjectorError: Нет поставщика для PickStoreCompComponent! NullInjectorError: StaticInjectorError (AppModule) [HomeCompComponent -> PickStoreCompComponent]: StaticInjectorError (Платформа: ядро) [HomeCompComponent -> PickStoreCompComponent]: NullInjectorError: нет поставщика для PickStoreComPort module.ts, ошибка исчезает, но next () не виден в подписках

pick-store-comp.component.ts

import { DataStorgeService } from 'src/app/data-storge.service';
import { Observable, Subject } from 'rxjs';

@Component({
  selector: 'app-pick-store-comp',
  templateUrl: './pick-store-comp.component.html',
  styleUrls: ['./pick-store-comp.component.scss']
})
export class PickStoreCompComponent implements OnInit {
  constructor(private data: DataStorgeService) {}

  storesfire = new Subject<any>();
  allCouponsData = [];
  selectedCoupon;
  onStoreClick() {
    this.storesfire.next(this.selectedCoupon);
  }

  ngOnInit() {
    this.allCouponsData = this.data.allCoupons;
  }
}

home-comp.component.ts

import { Component, OnInit } from '@angular/core';
import { PickStoreCompComponent } from '../pick-store-comp/pick-store-comp.component';

@Component({
  selector: 'app-home-comp',
  templateUrl: './home-comp.component.html',
  styleUrls: ['./home-comp.component.scss']
})
export class HomeCompComponent implements OnInit {
  constructor(private storesData: PickStoreCompComponent) {}

  ngOnInit() {
    this.storesData.storesfire.subscribe((data) => {
      console.log('test');
    });
  }
}

1 Ответ

1 голос
/ 04 марта 2020

Вы не вводите компоненты в другие компоненты. Компоненты могут взаимодействовать по-разному - это не один из них.

В вашем случае я бы порекомендовал общий сервис. Добавьте сервис в два компонента, которые взаимодействуют. Сервис создает тему. Один компонент отправляет значения в тему, другой подписывается.

store.service.ts

// declare singleton service so that both components use a shared instance
@Injectable({
  providedIn: 'root'
})
export class StoreService {
  // use ReplaySubject if you want subscribers to receive an 
  // existing value on subscription
  private storesFire = new ReplaySubject<any>(1);

  // prefer exposing the subject via your own API rather than directly

  getSelectedCoupon(): Observable<any> {
    return this.storesFire.asObservable();
  }

  selectCoupon(coupon) {
    this.storesFire.next(coupon);
  }
}

pick-store.component.ts

export class PickStoreCompComponent implements OnInit {
  constructor(private data: DataStorageService,
    private storeService: StoreService
  ) {}

  allCouponsData = [];
  selectedCoupon;

  onStoreClick() {
    this.storeService.selectCoupon(this.selectedCoupon);
  }

  ngOnInit() {
    this.allCouponsData = this.data.allCoupons;
  }
}

home. component.ts

export class HomeCompComponent implements OnInit {
  constructor(private storeService: StoreService) {}

  private destroyed = new Subject();

  ngOnInit() {
    this.storeService.getSelectedCoupon.pipe(
      // unsubscribe on destroy
      takeUntil(this.destroyed)
    ).subscribe((data) => {
      console.log(data);
    });
  }

  ngOnDestroy() {
    this.destroyed.next();
    this.destroyed.complete();
  }
}

...