首页 > 解决方案 > 属性 'brews' 没有初始化程序,也没有在构造函数中明确分配

问题描述

当我尝试运行我的项目时出现此错误,我尝试在 angularCompilerOptions 中设置 strictPropertyInitialization false 但它也不起作用我尝试设置!而是酿造 在此处输入图像描述

import { HttpService } from '../http.service';

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

   brews: Object; 

  constructor(private _http: HttpService) { }

  ngOnInit() {
    this._http.getBeer().subscribe(data  => {
      this.brews = data
      console.log(this.brews);
    });
  }

}
<h1>Breweries</h1>

<ul *ngIf="brews">
  <li *ngFor="let brew of brews">
    <p class="name">{{ brew.name }}</p>
    <p class="country">{{ brew.country }}</p>
    <a class="site" href="{{ brew.website_url }}">site</a>
  </li>
</ul> 

标签: angular

解决方案


我们也面临同样的错误。可能是 Angular 的不同版本造成的。

将 ListComponent 类更改为以下内容:

brews: Array<any> = [];

  constructor( private _http:HttpService) { }

  ngOnInit(): void {
    this._http.getBeer().subscribe(data => {
      this.brews = data as Array<Object>;
      console.log(this.brews);
    });
  }

这个答案归功于 ram64 在 youtube 上的评论。


推荐阅读