【发布时间】:2021-05-03 21:30:12
【问题描述】:
我在访问 Angular 项目中定义的变量时遇到问题。我是新手,但请耐心等待。 我的项目如下所示:
app.component.html:
<div>
<ul>
<li *ngFor='let var1 of Fcomponent' >{{var1}}</li>
</ul>
</div>
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'project';
}
variables1.component.ts:
import { Injectable } from "@angular/core";
@Injectable({
providedIn:'root'
})
export class Variables1Service{
Fcomponent: number[]=[0,1,2,3,4,5,6,7,8,9];
}
variables1.service.ts:
import { Injectable } from "@angular/core";
@Injectable({
providedIn:'root'
})
export class Variables1Service{
Fcomponent: number[]=[0,1,2,3,4,5,6,7,8,9];
}
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { Variables1Service } from './variables1.service';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [Variables1Service],
bootstrap: [AppComponent]
})
export class AppModule {}
现在我收到以下错误:
无法获取 /。 错误:src/app/app.component.html:3:27 - 错误 TS2339:“AppComponent”类型上不存在属性“Fcomponent”。
3
如何让它工作?
【问题讨论】:
-
您收到此错误是因为有多个 component.ts 文件引用 app.component.html。因此,要么您应该将 Fcomponent 数组移动到 app.component.ts,或者如果出于某种原因想要将其分开,您可以创建一个没有 @Compnent 装饰器的类并在 app.component.ts 中实例化该类。
-
Fcomponent在您的 app.component.ts 文件中不存在。实际上它位于您的 variables1.component.ts 文件中。现在,如果您想访问应用程序组件中的 Fcomponent,请将其移至服务文件并将服务作为依赖项添加到应用程序组件中。 -
我按照指示更新了项目,现在又遇到了一个障碍。任何提示如何走得更远?
-
您能否建议如何以及在何处添加对 Fcomponent 数组进行洗牌的函数? function shuffle(array){ for (let i=array.length-1;i>0;i--) { let j=Math.floor(Math.random()*(i+1)); [数组[i],数组[j]]=[数组[j],数组[i]]; } 返回数组;