属性“brews”没有初始值设定项,并且未在构造函数中明确分配

时间:2021-02-01 19:46:32

标签: angular

当我尝试运行我的项目时出现此错误,我尝试在 angularCompilerOptions 中设置 strictPropertyInitialization false 但它也不起作用我尝试设置!而是酿造 enter image description here

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> 

2 个答案:

答案 0 :(得分:1)

我们也面临同样的错误。可能是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 评论上。

答案 1 :(得分:0)

brews: Object; 表示必须始终设置 brews 并且始终是 Object。但是,如果它没有默认值并且未在构造函数中设置,则不可能出现这种情况。在最终通过您的 brews 回调设置之前,subscribe 会有一段时间没有值。

您需要允许 brews 可能是 undefinedbrews?: Object; 应该这样做。或者 brews: Object | undefined = undefined; 如果你想更明确。