0

Angular を使用して、さまざまなコンポーネントからいくつかの変数を共有するサービスがあります。このような:

import { Injectable } from "@angular/core";
import { BehaviorSubject } from "rxjs";
@Injectable()
@Injectable({
  providedIn: "root"
})

/**
 * Service to manage all the global variables in order to use it in different components
 */
export class SharedService {

  // Global variable of the path 
  private rPathSource = new BehaviorSubject(""); // Set up the source
  currentRPath = this.rPathSource.asObservable(); // Make it Observable

 constructor() {}

  /**
   * Function to change the global path from a component
   * @param path string of the path of the R Folder for the result of the ML
   */
  changeRPath(path: any) {
    this.rPathSource.next(path);
  }
}

次に、コンポーネントからサブスクライブします。このように: コンポーネント 1

constructor(private shared: SharedService) {}

ngOnInit() {
    this.shared.currentRPath.subscribe(RPath => {
      this.currentRPath = RPath;
      // HERE I DO A GET REQUEST
    });
  }

そして、別のコンポーネントから変数を次のように変更します: コンポーネント 2

this.shared.changeRPath("");

いくつかのボタンを備えたサイドナビゲーション バーがあり、各ボタンは URL と ng コンテンツが読み込まれたコンポーネントを変更します。

<ng-content></ng-content>

ボタンを押してコンポーネント 1 にリダイレクトすると、変数にサブスクライブし、get リクエストが実行されます。すべて順調。

問題は、ボタンを押してコンポーネント 2 にリダイレクトすると、共有変数が変更され、コンポーネント 1 にサブスクライブしているため、get リクエストが再度実行されることです。実際、get リクエストはサブスクライブのコールバックにあります。

しかし、奇妙なのは、コンポーネント 1 がコンポーネント 2 であるため、もうロードされていないことです。コンポーネントが変更されたときに破棄されることは想定されていません。

4

1 に答える 1