angular設置全局變量,修改監聽變量

建立service.module.tsmarkdown

import { NgModule, ModuleWithProviders } from '@angular/core';
import { SomeSharedService } from './global.service';
export {
  SomeSharedService
}

@NgModule()
export class ServicesModule { 
  static forRoot():ModuleWithProviders{
    return {
      ngModule:ServicesModule,
      providers:[SomeSharedService]
    }
  }
}

新建global.service.tsapp

import { Injectable } from '@angular/core'
import { BehaviorSubject } from 'rxjs';

@Injectable()
export class SomeSharedService {
  public globalVar:BehaviorSubject<any[]> = new BehaviorSubject([]);
  public pageLimit = 10;
}

在組件1中引入服務並獲取值ide

...
import { SomeSharedService } from 'src/app/services/global.service';
.....
  constructor(
    private someSharedService: SomeSharedService
  ) { 
  }

  ngOnInit() {
    this.someSharedService.globalVar.subscribe(d=>{
      this.clumb = d;
    })
  }
....
}

在組件2中引入服務並設置值post

import { SomeSharedService } from 'src/app/services/global.service';
....
...
  constructor(
    private someSharedService$:SomeSharedService
  ) {}

 
  getProjectName(id:Number){
    this.someSharedService$.globalVar.next(['個人項目',{id:id,name:res.data.project_name}]
  }
....
}

這裏設置了新的值,在組件1訂閱 到改變後的值。this

相關文章
相關標籤/搜索