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、任何好玩贰柒拾辅助透视是真的假的的玩...
出乎意料的是!川娱竞技血战辅助... 出乎意料的是!川娱竞技血战辅助器"揭露辅助教程"本来真的有挂(哔哩哔哩)1、超多福利:超高返利,海量...
2026版复盘!花花生活圈辅助... 2026版复盘!花花生活圈辅助工具安装教程"开挂辅助器"一直是有挂(哔哩哔哩)小薇(辅助器软件下载)...
攻略辅助挂!中至吉安小程序微信... 攻略辅助挂!中至吉安小程序微信小程序"透视辅助脚本"原来真的是有挂(哔哩哔哩)1.中至吉安小程序微信...
透视安卓版!天天爱消除辅助脚本... 透视安卓版!天天爱消除辅助脚本"解谜辅助脚本"切实是真的有挂(哔哩哔哩)1、让任何用户在无需天天爱消...
更值得关注的是!中至九江麻将辅... 更值得关注的是!中至九江麻将辅助器"揭幕辅助攻略"都是是有挂(哔哩哔哩)1、玩家可以在中至九江麻将辅...
透视了解!打两圈辅助"... 透视了解!打两圈辅助"解迷辅助插件"都是真的有挂(哔哩哔哩)小薇(辅助器软件下载)致您一封信;亲爱打...
黑科技技巧!有没有哈糖大菠萝攻... 黑科技技巧!有没有哈糖大菠萝攻略推荐"解谜辅助app"好像存在有挂(哔哩哔哩)1、下载好有没有哈糖大...
透视有挂!决战卡五星辅助&qu... 透视有挂!决战卡五星辅助"解迷辅助器"一直确实有挂(哔哩哔哩)1、每一步都需要思考,不同水平的挑战会...
最终!上饶中至能操控吗&quo... 最终!上饶中至能操控吗"分享辅助方法"一贯存在有挂(哔哩哔哩)上饶中至能操控吗透视方法中分为三种模型...