0
点赞
收藏
分享

微信扫一扫

【实用】Angular中如何实现类似Vuex的全局变量状态变化功能?


ng g s storage

storage.service.ts

import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class StorageService {
text = '初始值';
color = 'gray';
}

app.component.html、app.component.css、app.component.ts

<button (click)="storageService.text='全局改变后的值';storageService.color='red'">改变全局变量(文字变红色)</button>
<h1 [attr.color]="storageService.color">{{storageService.text}}</h1>
<app-other></app-other>

________________________________________________________________________________

[color="gray"] {
color: gray;
}
[color="red"] {
color: red;
}

________________________________________________________________________________

import { Component } from '@angular/core';
import { StorageService } from './services/storage.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public storageService: StorageService,) {}
}

components/other.component.html、components/other.component.css、components/other.component.ts 

<p>其他组件:</p>
<h1 [attr.color]="storageService.color">{{storageService.text}}</h1>

________________________________________________________________________________

[color="gray"] {
color: gray;
}
[color="red"] {
color: red;
}

________________________________________________________________________________

import { Component } from '@angular/core';
import { StorageService } from '../../services/storage.service';
@Component({
selector: 'app-other',
templateUrl: './other.component.html',
styleUrls: ['./other.component.css']
})
export class OtherComponent {
constructor(public storageService: StorageService,) {}
}

【实用】Angular中如何实现类似Vuex的全局变量状态变化功能?_Angular

点击按钮后

【实用】Angular中如何实现类似Vuex的全局变量状态变化功能?_全局变量_02

举报

相关推荐

0 条评论