gpt4 book ai didi

javascript - 具有构造函数以及 HTML 和 CSS 文件的组件数组。错误 NG2003。 ngFor

转载 作者:行者123 更新时间:2023-12-03 07:37:22 25 4
gpt4 key购买 nike

我的问题:我创建了一个 CardComponent,它就像一个带有 css 和 html 的卡片 View ,并且有一个构造函数。
我想在卡片数组(它的类型)中使用它。我使用服务来存储卡的数据。
家庭比较正在使用该服务并使用 ngFor 循环,这是代码.. 下面是我得到的错误...
有没有另一种使用它的方法,所以它会起作用?
card.component.ts:

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

@Component({
selector: 'app-card',
templateUrl: './card.component.html',
styleUrls: ['./card.component.css']
})
export class CardComponent{
imageSrc : string;
title : string;

constructor(imgSrc : string, title : string) {
this.imageSrc = imgSrc;
this.title = title;
}

ngOnInit(): void {
}
卡片服务.ts:
import { CardComponent } from './card/card.component';

export class CardsService{
ctgryCards : CardComponent[] = [
new CardComponent("https://cdn3.iconfinder.com/data/icons/outline-amenities-icon-set/64/Beauty_Saloon-512.png", "Beauty"),
new CardComponent("https://www.pinclipart.com/picdir/middle/391-3917890_get-business-value-from-sustainable-data-electronics-icon.png", "Electronics")
];

getAllCtgryCards(){
return this.ctgryCards.slice();
}
}
home.component.ts:
import { Component, OnInit } from '@angular/core';
import { CardComponent } from '../card/card.component';
import { CardsService } from '../cards.service';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
categoryCards : CardComponent[] = [];
constructor(private cardsServ : CardsService) { }

ngOnInit(): void {
this.categoryCards = this.cardsServ.getAllCtgryCards();
}
}
home.component.html:
<app-card *ngFor = "let card of categoryCards"></app-card>
错误 NG2003:

ERROR in src/app/card/card.component.ts:12:15 - error NG2003: Nosuitable injection token for parameter 'imgSrc' of class'CardComponent'. Found string

constructor(imgSrc : string, title : string) {

最佳答案

card.component.ts:
将构造函数更新为

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

constructor(@Inject(String) private imgSrc : string, title : string)
//import { Inject } from '@angular/core';

constructor(@Inject('imgSrc') private imgSrc : string, title : string)
根据 https://angular-2-training-book.rangle.io/di/angular2/inject_and_injectable ; @Inject() 是一种手动机制,用于让 Angular 知道必须注入(inject)参数。 @Inject 装饰器仅用于注入(inject)原语。
原始类型是 数字、字符串、 bool 值、大整数、符号、空值、未定义。

关于javascript - 具有构造函数以及 HTML 和 CSS 文件的组件数组。错误 NG2003。 ngFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62608292/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com