首页 > 解决方案 > 角度组件问题

问题描述

在过去的几天里,我一直被这段代码所困扰。我已经尝试卸载并重新安装。根据我的导师的说法,代码是正确的,并且在他的计算机上运行良好,所以不明白为什么这对我来说是个难题。

错误信息

app.component.ts:

import { Component } from '@angular/core';
import { ProductService } from './product.service';
@Component({
  selector: 'app-root',
  templateUrl: 
  `<h1>{{ title }}</h1>
  <products></products>`,
  providers: [ProductService]
  
})
export class AppComponent {
  title = 'sports';
}

产品.service.ts:

export class ProductService{
    getProducts() : string[] {
        return ["Los Angeles Kings - Hockey","Anaheim Ducks - Hockey","Los Angeles Dodgers - Baseball","Los Angeles Angels of Anaheim - Baseball","San Diego Padres - Baseball"];
    }
}

products.component.ts

import { Component } from '@angular/core'
import { ProductService} from './product.service'

@Component({
    selector: 'products',
    template: `
        <h2>Products</h2>
        <ul>
            <li *ngFor="let product of products">
                {{product}}
            </li>
        </ul>
})
export class ProductsComponent{
    products;

    constructor(productService: ProductService){
        this.products = productService.getProducts();
    }
} 

app.module.ts:

app.module.ts

标签: angulartypescript

解决方案


您需要在组件装饰器中使用template而不是。templateUrl

关于template

Angular 组件的内联模板。如果提供,请勿使用 templateUrl 提供模板文件。

@Component({
  selector: 'app-root',
  template: `
    <h1>{{ title }}</h1>
    <products></products>
  `,
  providers: [ProductService]
})
...

还要检查:

  • ProductsComponent是您的模块的一部分(declarations例如添加到数组中AppModule

推荐阅读