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;
  }
}

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

相关内容

热门资讯

一分钟了解!epoker有透视... 一分钟了解!epoker有透视吗(辅助挂)原来存在有挂(有人有挂)1、epoker有透视吗脚本辅助下...
热点讨论!wepoker辅助器... 热点讨论!wepoker辅助器有哪些功能(辅助挂)果然存在有挂(有挂方法)该软件可以轻松地帮助玩家将...
揭秘关于!wejoker透视方... 揭秘关于!wejoker透视方法(辅助挂)原来是真的有挂(有挂透明挂)1、在wejoker透视方法插...
玩家必看秘籍!hhpoker透... 玩家必看秘籍!hhpoker透视工具(辅助挂)竟然真的有挂(真是有挂)1、任何hhpoker透视工具...
科普常识!拱趴大菠萝机器人(辅... 科普常识!拱趴大菠萝机器人(辅助挂)确实有挂(今日头条)1、金币登录送、破产送、升级送、活动送。详细...
教程攻略!wepoker底牌透... 教程攻略!wepoker底牌透视(辅助挂)确实有挂(有挂解密)1、这是跨平台的wepoker底牌透视...
实测发现!werplan怎么作... 您好,werplan怎么作弊这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】...
揭秘一下!hhpoker作弊码... 揭秘一下!hhpoker作弊码(辅助挂)总是是真的有挂(有挂实锤);hhpoker作弊码辅助器是一种...
推荐一款!newpoker脚本... 推荐一款!newpoker脚本(辅助挂)都是存在有挂(有挂分享)newpoker脚本脚本下载中分为三...
一分钟揭秘!wepoker养号... 一分钟揭秘!wepoker养号规律(辅助挂)切实是有挂(有挂方法)1、wepoker养号规律辅助器安...