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

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

相关内容

热门资讯

aapoker辅助工具ai!a... aapoker辅助工具ai!aapoker辅助器,(aaPOKER)一直存在有挂,普及教程(黑科技攻...
wpk职业代打!wpk辅助外挂... wpk职业代打!wpk辅助外挂,(Wpk)果然真的有挂,总结教程(黑科技辅助器);1、该软件可以轻松...
wepoke软件规律!wepo... wepoke软件规律!wepoke有没有挂,(wePoke)一直是有挂,曝光教程(黑科技插件);1、...
wepoke辅助挂!wepok... wepoke辅助挂!wepoke透明黑科技,(wepoKE)好像存在有挂,切实教程(黑科技助手)1、...
wepoke黑科技ai!wep... wepoke黑科技ai!wepoke辅助软件靠谱吗,(we-poker)总是存在有挂,安装教程(黑科...
德州ai辅助软件排名!ai德州... 德州ai辅助软件排名!ai德州辅助软件,(德州之星)竟然真的有挂,大神讲解(黑科技黑科技);该软件可...
wpkai辅助有没有用!wpk... wpkai辅助有没有用!wpk到底有没有外挂,(wpK)一直是真的有挂,普及教程(黑科技透明挂)1、...
德扑ai助手!德扑之星ai代打... 德扑ai助手!德扑之星ai代打真假,(德扑ai)一贯是有挂,黑科技教程(黑科技技巧);1、进入到德扑...
wpk黑科技被锤原因!wpk智... wpk黑科技被锤原因!wpk智能ai,(wpK)其实是真的有挂,德州教程(黑科技助手);1、不需要A...
WPK辅助器的使用教程!wpk... WPK辅助器的使用教程!wpk ai辅助靠谱吗,(Wpk)切实是真的有挂,详细教程(黑科技工具);1...