Search code examples
angulardependency-injectionangular-material2angular-servicesangular-module

Angular 5: Service to share data between Components (across Modules)?


I have this simple Service which is a provider in two Modules:

@Injectable()
export class PlatformPickerService {
  platforms: string[] = [
    'macOS', 'Linux', 'Windows'
  ];
  public platform: string;

  constructor() {
    this.platform = this.platforms[1];
  }

  public getPlatform(): string {
    const platform = localStorage.getItem('platform');
    return platform == null ? this.platform : platform;
  }

  public setPlatform(platform: string) {
    this.platform = platform;
    localStorage.setItem('platform', platform);
  }
}

Unfortunately, nowhere I use it acquired the chosen value. Using it outside its Module gives only the default value, using it inside its Module gives no value.

Full test-case: https://stackblitz.com/edit/angular-aru94g-2djexv


Solution

  • Finally got it working: https://angular-aru94g-w6qy21.stackblitz.io (edit)

    Major changes were:

    Component

    updateService(event: any) {
        if (event.value != null) this.platformPickerService.setPlatform(event.value);
    }
    
    <mat-form-field>
      <mat-select placeholder="Platform" shouldLabelFloat="false"
                  [(ngModel)]="platformSelectd"
                  (selectionChange)=updateService($event)>
        <mat-option *ngFor="let platform of platformPickerService.platforms"
                    [value]=platform>
          {{ platform }}
        </mat-option>
      </mat-select>
    </mat-form-field>
    

    Module

    • Only have PlatformPickerService in one Module (app.module)

    Now it's time to try rewriting the setters/getters once more and see if that'll work (setPlatform to set platform) =3