【问题标题】:Create a class in Angular and use it in a component to assign values在 Angular 中创建一个类并在组件中使用它来分配值
【发布时间】:2020-06-12 06:26:45
【问题描述】:

国家级.ts

export class CountryClass {
  name: string;
  states: string[];
  cities: string[];
}

这是我创建的类。 但现在我无法在其他组件中使用。

这是

组件:主页.component.ts

import { Component, OnInit } from '@angular/core';
import {CountryClass} from '../country-class';

@Component({
  selector: 'app-home-page',
  templateUrl: './home-page.component.html',
  styleUrls: ['./home-page.component.css']
})
export class HomePageComponent implements OnInit {
  countryString:CountryClass[] [
    { 'name' :"India",
    statename :['Odish','WestBengal'],
    cities:['Bhubaneswar','Kolkata'];}
  ]

  constructor(private country:CountryClass) { }

  ngOnInit() {
  }
}

在此组件中使用类的属性时遇到错误。也许我遗漏了一些东西。 我得到的错误是:

provide your error here

我在 1 年后使用 angular,但我猜几乎忘记了它的基本知识,甚至找不到任何正确的答案。 如果有人能帮我解决这个问题,那就太好了。

【问题讨论】:

  • 你遇到了什么错误?
  • 另外 - 您是否直接从您的代码中复制了这个?因为有几个格式问题。你可以在 stackblitz 中重新创建吗?
  • @KurtHamilton app.component.ts 有代码并检查类的模型文件夹。
  • @KurtHamilton stackBlitz 没有显示错误,但我的 vscode 显示了。

标签: angular typescript class components angular-components


【解决方案1】:

constructor(private country: CountryClass) { } 如果你在组件的构造函数中传递一些东西,它就是dependency。注入器解析您的依赖项,并尝试解析您未标记为可注入且未注册为提供程序的CountryClass。我想你只是想添加一个私有字段。像往常一样做,而不是从构造函数。

【讨论】:

  • 谢谢。我从构造函数中删除了它
  • @PrabhuDuttaMishra 请记住,您可以从构造函数定义类字段,但仅适用于您的自定义类并且仅当您手动创建这些类的实例时。对于组件、服务、模块、管道等,你不能这样做。因为您不创建组件和服务的实例,所以注入器会这样做。
【解决方案2】:

通过添加将 CountryClass 类设为服务类

@Injectable({
  providedIn: 'root'
})
export class CountryClass {
  name: string;
  states: string[];
  cities: string[];
}

【讨论】:

  • 我不想把它变成服务
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2013-08-22
相关资源
最近更新 更多