首页 > 解决方案 > 角度错误 TS2341:属性“X”是私有的,只能在类内访问

问题描述

我正在做一个角度课程的练习代码。

该应用程序有效,但我的 mac 终端出现此错误,我完全按照课程所示进行操作,找不到问题所在。

Error: src/app/components/articles/articles.component.html:1:22 - error TS2341: Property 'articles' is private and only accessible within class 'ArticlesComponent'.

1 <h3>Repositorios : {{articles.articlesCount}}</h3>

这是我的服务:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';


@Injectable({
  providedIn: 'root'
})
export class ArticleService {
    public articlesCount : number = 30;

    constructor(private http: HttpClient) { }

    public getAll(){
            this.http.get('https://api.github.com/users/codigofacilito/repos').subscribe(data=> {
            console.log(data);
    })
}}

下面是使用服务的 article.component:

import { Component, OnInit } from '@angular/core';
import {ArticleService} from '../../services/article.service';


@Component({
  selector: 'app-articles',
  templateUrl: './articles.component.html',
  styleUrls: ['./articles.component.css']
})
export class ArticlesComponent implements OnInit {

    constructor(private articles : ArticleService) { }

    ngOnInit(){
      this.articles.getAll();
    }

}

和视图 HTML:

<h3>Repositorios : {{articles.articlesCount}}</h3>

标签: angularservice

解决方案


HTML 模板可以访问component文件中定义的变量。

您没有articlesarticle.component.ts

进行以下更改:

export class ArticlesComponent implements OnInit {

public articles: any; // provide correct type 
constructor(private articleService : ArticleService) { }

ngOnInit(){
    this.articleService.getAll().subscribe((result)=>{
       this.articles = result
   })
}

}

并在服务文件中:

 public getAll(){
       return this.http.get('https://api.github.com/users/codigofacilito/repos')
}

推荐阅读