打字稿 - 类型'false'不能指定为'true'类型

Lef*_*eff 10 typescript angular

我正在学习角度2,在这个例子中,我将isLoading的变量设置为true,然后将其更改为false,一旦我获取了我需要的数据,我得到错误:

打字稿 - 类型'false'不能指定为'true'类型

这是代码:

export class AppComponent implements OnInit {
    isLoading: true;

    constructor(private _articleService: ArticleService, private _postService: PostService){}

    ngOnInit(){
      this.articles = this._articleService.getArticles();
      this._postService.getPosts()
        .subscribe(posts => {
          this.isLoading = false;
          console.log(posts[0].title);
        });
    }
Run Code Online (Sandbox Code Playgroud)

Yoa*_*man 13

不需要一次定义变量的类型,但是您应该设置在开发期间查找错误.另外编辑器在知道完成代码之前就知道了变量的类型.

export class AppComponent implements OnInit {
isLoading : boolean =  true;

constructor(private _articleService: ArticleService, private _postService: PostService){}

ngOnInit(){
  this.articles = this._articleService.getArticles();
  this._postService.getPosts()
    .subscribe(posts => {
      this.isLoading = false;
      console.log(posts[0].title);
    });
}
Run Code Online (Sandbox Code Playgroud)


Lou*_*uis 8

isLoading: true;意味着您可以分配的唯一值isLoading是值true.你想要的isLoading: boolean.


Lef*_*eff 5

根据评论的建议和@Louis的答案,这是修复此错误的正确语法:

isLoading: boolean = true;
Run Code Online (Sandbox Code Playgroud)