【问题标题】:Property 'brews' has no initializer and is not definitely assigned in the constructor属性 'brews' 没有初始化程序,也没有在构造函数中明确分配
【发布时间】:2021-05-06 00:15:39
【问题描述】:

当我尝试运行我的项目时出现此错误,我尝试在 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


    【解决方案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 上的评论。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 如果我这样做了,我得到了这个错误:“类型'对象'不可分配”
      • 屏幕截图中的其他错误之一是告诉您Object 不是一个好用的类型。它是对象构造函数。您可能打算使用小写的object。但是,如果您可以为该特定对象使用类型,那就更好了。
      猜你喜欢
      • 2021-04-13
      • 2021-05-21
      • 2021-08-14
      • 2021-02-28
      • 2021-12-25
      相关资源
      最近更新 更多