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、每一步都需要...
外挂法子!德州来玩辅助器,we... 外挂法子!德州来玩辅助器,werplan有挂吗-一贯一直总是有辅助教程(哔哩哔哩)1、打开软件启动之...
外挂教材!哈糖大菠萝有挂吗5个... 外挂教材!哈糖大菠萝有挂吗5个常用方法,德普辅助器怎么用-本来是真的有辅助技巧(哔哩哔哩)1、进入到...
外挂演示!来玩app破解,po... 外挂演示!来玩app破解,pokermaster脚本-果然一直都是有辅助app(哔哩哔哩)1、这是跨...
外挂课程!约局吧app有挂吗,... 外挂课程!约局吧app有挂吗,拱趴大菠萝机器人-其实一直总是有辅助脚本(哔哩哔哩)1、拱趴大菠萝机器...
外挂技法!佛手在线大菠萝智能辅... 外挂技法!佛手在线大菠萝智能辅助器,拱趴大菠萝万能辅助器-原来真的有辅助方法(哔哩哔哩)暗藏猫腻,小...
外挂绝活!德普之星私人局辅助器... 外挂绝活!德普之星私人局辅助器,拱趴大菠萝挂怎么安装-原来是有辅助app(哔哩哔哩)1、拱趴大菠萝挂...
外挂模块!德州透视插件,佛手大... 外挂模块!德州透视插件,佛手大菠萝13道挂哪里-好像是真的有辅助工具(哔哩哔哩)1、佛手大菠萝13道...
外挂手册!xpoker辅助,德... 外挂手册!xpoker辅助,德普之星的辅助工具介绍-确实真的有辅助软件(哔哩哔哩)1、在xpoker...
外挂妙招!德普之星透视,德普之... 外挂妙招!德普之星透视,德普之星私人局辅助器-总是是有辅助app(哔哩哔哩)所有人都在同一条线上,像...