Angular类多个错误,与似乎是服务注入有关
创始人
2024-10-27 23:01:30
0

这个问题通常出现在有多个类需要注入同一个服务的情况下。解决这个问题需要确认代码中是否存在多个类使用了同一个服务,并且在注入时会出现冲突。如果是这个问题导致的,则需要在相关类中为服务实现单例模式。下面是一个示例:

app.module.ts:

import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { UserService } from './user.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [
    UserService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

user.service.ts:

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  private user: Object;

  constructor() { }

  setUser(user: Object) {
    this.user = user;
  }

  getUser(): Object {
    return this.user;
  }
}

example-component-one.component.ts:

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-example-component-one',
  templateUrl: './app-example.component.html',
  styleUrls: ['./app-example.component.css'],
  providers: [UserService]
})
export class ExampleComponentOne implements OnInit {
  private user: Object;

  constructor(private userService: UserService) { }

  ngOnInit(): void {
    this.user = {name: 'John', age: 30};
    this.userService.setUser(this.user);
  }
}

example-component-two.component.ts:

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';

@Component({
  selector: 'app-example-component-two',
  templateUrl: './app-example.component.html',
  styleUrls: ['./app-example.component.css'],
  providers: [UserService]
})
export class ExampleComponentTwo implements OnInit {
  private user: Object;

  constructor(private userService: UserService) { }

  ngOnInit(): void {
    this.user

相关内容

热门资讯

有挂方略辅助!wepoker辅... wepoker辅助器是一款专注玩家量身打造的游戏记牌类型软件,在wepoker辅助器这款游戏中我们可...
有人有挂开挂!四川途游辅助软件... 有人有挂开挂!四川途游辅助软件瞎子啊,边锋老友内蒙古辅助(透视好牌开挂辅助软件)>>您好:软件加薇1...
竟然有挂开挂!四川熊猫辅助软件... 竟然有挂开挂!四川熊猫辅助软件,潮汕掌上娱破解(玩家攻略开挂辅助工具);四川熊猫辅助软件免费下载原版...
有挂解惑辅助!拼三张辅助器,陕... 较多好评“微乐万能挂官网”开挂(透视)辅助教程 了解更多开挂安装加(136704302)微信号是一款...
有挂存在辅助!微乐小程序辅助器... 有挂存在辅助!微乐小程序辅助器脚本,新道游正版辅助(交流学习经验开挂辅助软件)>>您好:软件加薇13...
有挂猫腻开挂!多乐游戏小程序辅... 有挂猫腻开挂!多乐游戏小程序辅助,微乐家乡自建房辅助app(一起来探讨开挂辅助工具);无需打开直接搜...
真是有挂辅助!手机脚本辅助软件... 手机脚本辅助软件是一款可以让一直输的玩家,快速成为一个“必胜”的ai辅助神器,有需要的用户可以加我微...
有挂方法开挂!朋朋政和麻将为什... 朋朋政和麻将为什么一直输是一款专注玩家量身打造的游戏记牌类型软件,在朋朋政和麻将为什么一直输这款游戏...
有挂攻略开挂!老友广东麻将有没... 有挂攻略开挂!老友广东麻将有没有假,来物局潮汕辅助(透视智能ai开挂辅助安装) 【无需打开直接搜索加...
有挂总结辅助!宝宝浙江辅助工具... 有挂总结辅助!宝宝浙江辅助工具,永胜联盟金花辅助(玩家必看分享开挂辅助软件);无需打开直接搜索打开薇...