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

相关内容

热门资讯

今日头条!微信老友广东辅助器,... 今日头条!微信老友广东辅助器,微乐福建辅助器,安装教程(原来有开挂辅助器)是一款可以让一直输的玩家,...
每日必看推荐!微信小程序家乡大... 每日必看推荐!微信小程序家乡大二辅助工具,新西游辅助器,透视教程(原来有开挂辅助安装);1、选手技艺...
玩家亲测!广东插件智能插件安装... 玩家亲测!广东插件智能插件安装包免费,wepoker轻量版有透视吗,详细教程(原来有开挂辅助挂);广...
重大通报!哈糖大菠萝开挂,we... 重大通报!哈糖大菠萝开挂,we-poker是什么软件,解密教程(原来有开挂辅助助手);1.哈糖大菠萝...
解密关于!鱼乐达人辅助修改器,... 解密关于!鱼乐达人辅助修改器,下载微乐小程序自建房透视,介绍教程(原来有开挂辅助软件);解密关于!鱼...
重大发现!四川家园游戏辅助,微... 重大发现!四川家园游戏辅助,微乐自建房辅助多少钱一个月,AI教程(原来有开挂辅助器);微乐自建房辅助...
玩家必用!玉海楼茶苑怎么开挂,... 玩家必用!玉海楼茶苑怎么开挂,天酷互娱有辅助工具嘛,黑科技教程(原来有开挂辅助插件);天酷互娱有辅助...
一分钟教你!椰岛常胜游戏破解,... 一分钟教你!椰岛常胜游戏破解,广东雀神透视,解密教程(原来有开挂辅助下载);椰岛常胜游戏破解软件透明...
实测发现!三江互娱辅助,wpk... 实测发现!三江互娱辅助,wpk显示有透视挂,详细教程(原来有开挂辅助助手),三江互娱辅助是用手机号来...
程序员教你!长春科乐第三方辅助... 程序员教你!长春科乐第三方辅助工具,wepoker代打辅助机器人,曝光教程(原来有开挂辅助黑科技);...