无法使用Angular 2中的subscribe()方法为变量赋值

时间:2016-09-15 03:40:59

标签: angular

承诺返回一个值,但我似乎没有在subscribe方法中正确分配值。

import { Component } from '@angular/core';
import { DataService } from '../../shared/data.service';

@Component({
  selector: 'topbar',
  templateUrl: './src/app/components/topbar/topbar.component.html',
  styleUrls: ['./src/app/components/topbar/topbar.component.css'],
  providers: [DataService]
})

export class TopbarComponent {
  companyCount;

  constructor (private dataService: DataService){
    dataService.getCompaniesCount().subscribe(res => this.companyCount = res.count); //doesn't work
    dataService.getCompaniesCount().subscribe(res => console.log(res.count)); //works    
  }
}

3 个答案:

答案 0 :(得分:10)

使用此代码

export class TopbarComponent {
  companyCount;

  constructor (private dataService: DataService){
    dataService.getCompaniesCount().subscribe(res => this.companyCount = res.count); //doesn't work
    dataService.getCompaniesCount().subscribe(res => console.log(res.count)); //works    
  }
}

res => this.companyCount = res.count不会立即执行。 当getCompaniesCount()向服务器发出请求时,它需要时间,直到响应到达并且observable调用传递给subscribe(...)res => this.companyCount = res.count)的函数。

在响应到来之前,构造函数ngOnInitngAfterViewInit()以及许多其他内容的执行将会发生。

你可以看到

subscribe(res => this.companyCount = res.count)

就像注册事件发生时调用的事件处理程序一样。

所有依赖于可用数据的代码都需要正确链接。

最简单的方法是将代码转移到subscribe(...)

  constructor (private dataService: DataService){
    dataService.getCompaniesCount().subscribe(res => {
      this.companyCount = res.count); 
      // more code that depends on `res.count` being set goes here
    });
    dataService.getCompaniesCount().subscribe(res => console.log(res.count)); //works    
  }

答案 1 :(得分:1)

我知道线程已经过时了。所以,这适用于现在正在尝试的新用户。我不确定这是否是您正在寻找的东西。 但是我们可以将数据保存在组件变量中,尽管这是一种丑陋的解决方法。以下是我们在样本POC中使用的方法

(请使用正确的钩子,因为在构造函数中不喜欢将observable附加到obvisable)

";
        print_r($graphNode);
    echo "

那是样本组件,下面是样本服务

        @Component({
  selector: 'app-search-promo',
  templateUrl: './search-promo.component.html',
  styleUrls: ['./search-promo.component.css']
})
export class SearchPromoComponent implements  AfterViewInit {
  searchGroup: FormGroup;
  stringify  =  require('json-stringify-safe');
  someResult:any;
  resp:Response;
  localInput = new FormControl('', Validators.required);
  consumedPromoList: Observable<Promotion[]>;
  constructor(private searchService: SearchService, fb: FormBuilder) {
    this.searchGroup = fb.group({
      'localInput': this.localInput
    });
     this.stringify = require('json-stringify-safe');
     this.searchService.getPromoList().subscribe(
       resp => {
         this.someResult = <Promotion[]>resp;
         console.log("Inside sub in comp"+this.stringify(resp));
         console.log("before calling the methid");
         this.callDto(<Promotion[]>resp);
       }
     );
     console.log('inside const()' + this.stringify(this.someResult));
   }

callDto(data){
    console.log("caling"+data);
    this.someResult = <Promotion[]>data;
    console.log("Now priting:"+this.someResult);
    this.anotherMethod();
  }

  anotherMethod(){
    console.log("Inside another method"+this.stringify(this.someResult));
  }
}

答案 2 :(得分:0)

subscribe()内部没有组件上下文“ this”,要解决此问题,请声明_this并将其分配到subscribe()之前,如下所示;

    constructor (private dataService: DataService){
           const _this = this;
           dataService.getCompaniesCount().subscribe(res => {
              this.companyCount = res.count; // does't work
           });
           dataService.getCompaniesCount().subscribe(res => { _this.companyCount = res.count; //works
        });
}