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

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

什么是Vuex?只需三分钟!只需创建一个vuex.js文件,让你马上学会使用Vuex,尽管Vuex是个鸡肋!(扔掉store文件夹和里面的index、getters、actions、mutations等js文件吧!)_你挚爱的强哥❤给你发来1条消息❤-CSDN博客https://s-z-q.blog.csdn.net/article/details/119792336

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


{ {storageService.text}}

________________________________________________________________________________[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 

其他组件:

{ {storageService.text}}

________________________________________________________________________________[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,) {} }

点击按钮后

更多相关: