angular无法将值设置给公共变量。
创始人
2024-10-30 01:31:15
0

在Angular中,可以使用服务(Service)来共享数据和状态,而不是直接将值设置给公共变量。以下是一个示例解决方法:

  1. 创建一个服务(service)来共享数据:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class DataService {
  public sharedValue: any;

  constructor() { }
}
  1. 在需要共享数据的组件中注入该服务:
import { Component } from '@angular/core';
import { DataService } from '路径/data.service';

@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.css']
})
export class ExampleComponent {

  constructor(private dataService: DataService) { }

  setValue(value: any) {
    this.dataService.sharedValue = value;
  }
}
  1. 在其他需要访问该共享数据的组件中再次注入该服务,并使用该服务中的共享变量:
import { Component } from '@angular/core';
import { DataService } from '路径/data.service';

@Component({
  selector: 'app-another-example',
  templateUrl: './another-example.component.html',
  styleUrls: ['./another-example.component.css']
})
export class AnotherExampleComponent {
  sharedValue: any;

  constructor(private dataService: DataService) { }

  getValue() {
    this.sharedValue = this.dataService.sharedValue;
  }
}

通过使用服务来共享数据,可以避免直接设置公共变量的问题,并且可以在整个应用程序中共享数据和状态。

相关内容

热门资讯

五分钟了解!小程序蜀山西川血战... 五分钟了解!小程序蜀山西川血战辅助!其实一直都是有辅助神器(竟然有挂)-哔哩哔哩小程序蜀山西川血战辅...
第四分钟了解!多乐辅助器使用教... 第四分钟了解!多乐辅助器使用教程!竟然一直都是有辅助教程(有挂方法)-哔哩哔哩1、多乐辅助器使用教程...
第2分钟了解!川南久久辅助!确... 第2分钟了解!川南久久辅助!确实存在有辅助教程(竟然有挂)-哔哩哔哩1、川南久久辅助辅助软件下载优化...
第3分钟了解!jj斗地主麻将外... 您好,jj斗地主麻将外g挂这款游戏可以开挂的,确实是有挂的,需要了解加去威信【485275054】很...
第九分钟了解!多乐跑的快脚本!... 第九分钟了解!多乐跑的快脚本!总是存在有辅助工具(有挂辅助)-哔哩哔哩1、多乐跑的快脚本公共底牌简单...
三分钟了解!蜀山四川怎么提高胜... 三分钟了解!蜀山四川怎么提高胜率!好像一直都是有辅助教程(有挂神器)-哔哩哔哩1、每一步都需要思考,...
2分钟了解!新518互游脚本!... 2分钟了解!新518互游脚本!切实存在有辅助教程(有挂辅助)-哔哩哔哩1、不需要AI权限,帮助你快速...
第2分钟了解!打罗松必胜技巧!... 第2分钟了解!打罗松必胜技巧!一直是有辅助技巧(有挂教学)-哔哩哔哩一、打罗松必胜技巧可以开透视的定...
6分钟了解!约战青山晃晃辅助器... 6分钟了解!约战青山晃晃辅助器!本来存在有辅助插件(有挂细节)-哔哩哔哩1、用户打开应用后不用登录就...
八分钟了解!九天大厅辅助器!原... 八分钟了解!九天大厅辅助器!原来一直都是有辅助软件(有挂细节)-哔哩哔哩小薇(辅助器软件下载)致您一...