簡體   English   中英

可變可用性,function 聲明

[英]Variable availability, function declaration

我在訪問 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';
  }

變量1.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];
}

變量1.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 <li *ngFor='let var1 of Fcomponent' >{{var1}}

如何讓它工作?

在 app.component.ts 里面:

export class AppComponent {
  title = 'project';

需要添加以下代碼:

  private variables1Service:Variables1Service;

  constructor (){
    this.variables1Service=new Variables1Service();
  }

  get Fcomponent() {
    return this.variables1Service.Fcomponent;
  }

一切都開始正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM