Can';t在Angular 2中使用subscribe()方法为变量赋值

Can';t在Angular 2中使用subscribe()方法为变量赋值,angular,Angular,promise返回一个值,但我似乎没有在subscribe方法中正确地赋值 import { Component } from '@angular/core'; import { DataService } from '../../shared/data.service'; @Component({ selector: 'topbar', templateUrl: './src/app/components/topbar/topbar.component.html', styleU

promise返回一个值,但我似乎没有在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    
  }
}
使用此代码

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()
向服务器发出请求时,需要很长的时间,直到响应到达,可观察的调用传递给
subscribe(…)
res=>this.companyCount=res.count
)的函数

构造函数的执行,
ngOnInit
ngAfterViewInit()
和许多其他东西都会在响应到达之前发生

你可以看到

subscribe(res => this.companyCount = res.count)
类似于注册事件发生时调用的事件处理程序

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

最简单的方法是将代码移动到
subscribe(…)


我知道这根线是旧的。因此,这是为正在尝试的新用户准备的。我不确定这是否是你正在寻找的东西。 但我们可以将数据持久化到组件变量中,尽管这是一个难看的解决方法。下面是我们如何在示例POC中使用

(请使用适当的挂钩,因为在构造函数中不首选对可观察对象进行细分)

@组件({
选择器:“应用程序搜索促销”,
templateUrl:'./search promo.component.html',
样式URL:['./搜索promo.component.css']
})
导出类SearchPromoComponent实现AfterViewInit{
搜索组:FormGroup;
stringify=require('json-stringify-safe');
一些结果:任何;
resp:响应;
localInput=新表单控件(“”,需要验证程序);
消费者列表:可观察;
构造函数(私有searchService:searchService,fb:FormBuilder){
this.searchGroup=fb.group({
“localInput”:this.localInput
});
this.stringify=require('json-stringify-safe');
此.searchService.getPromoList().subscribe(
resp=>{
this.someResult=resp;
控制台日志(“组件中的内部子组件”+此字符串化(resp));
log(“调用methid之前”);
这是我的电话号码(resp);
}
);
log('inside const()'+this.stringify(this.someResult));
}
callDto(数据){
控制台日志(“校准”+数据);
this.someResult=数据;
log(“Now priting:+this.someResult”);
这是一种新的方法();
}
anotherMethod(){
log(“在另一个方法内”+this.stringify(this.someResult));
}
}
这是示例组件,下面是示例服务

@Injectable()
export class SearchService {
  getUrl: String = './../assets/promotionList.json';
  subject: BehaviorSubject<Promotion[]> = new BehaviorSubject([]); // initialize with an empty response[]
  subjectAsObservable;
   someResult;
   promoList:Promotion[];
  constructor(private http: HttpClient) {
    this.getPromoList();
    console.log("after first");
    this.getPromoValues();
    console.log("after second call");
  }

    getPromoList(){
    // by default it emits a response of Json and hence Observabpe<PromotionList>
    // throws an error
    this.someResult = this.http.get(`${this.getUrl}`);
    console.log("before map"+<Observable<Promotion[]>> this.someResult);
    return (<Observable<Promotion[]>> this.someResult);
    //console.log("first subsriber"+JSON.stringify (this.someResult);

  }
@Injectable()
导出类搜索服务{
getUrl:String='./../assets/promotionList.json';
主题:BehaviorSubject=新的BehaviorSubject([]);//使用空响应初始化[]
可观察的主体;
某些结果;
促销员:促销[];
构造函数(专用http:HttpClient){
这个.getPromoList();
console.log(“第一次之后”);
此参数为.getPromoValues();
console.log(“第二次调用后”);
}
getPromoList(){
//默认情况下,它会发出一个Json响应,从而观察ABPE
//抛出错误
this.someResult=this.http.get(`${this.getUrl}`);
log(“映射前”+this.someResult);
返回(this.someResult);
//log(“第一个subscriber”+JSON.stringify(this.someResult);
}
组件上下文“this”在subscribe()中不可用,要解决此问题,请在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
        });
}

ypu所说的“不工作”是什么意思?它确实工作。在
console.log(this.companyCount)
中赋值检查值后,我认为应该在ngOnInit()中调用getcompanycount,其中一些代码是.subscribe(res=>{console.log(res.count);this.companyCount=res.count;})。感谢您的精彩回复。我仍在学习这方面的新知识。因此,该值是按照micronyks的建议分配的,正如您所说的Günter,问题与响应的时间有关。感谢你们两位帮助我理解这一点。我认为问题在于html(topbar.component.html)正在尝试在分配值之前使用companyCount。是否有我缺少的解决此问题的最佳做法?“正在尝试在分配值之前使用companyCount”从服务器获取数据时通常会出现这种情况。您可以使用
..
包装内容,以便
中的部分在数据可用或使用之前不会呈现(如我在
*ngIf
中所述)安全导航操作符。
?。
通过这种方式,
之后的属性仅在前面的表达式为
!=null
@GünterZöchbauer时才计算。是否有其他方法等待响应以typescript形式到达?不确定您的意思。该方法有什么问题?
@Injectable()
export class SearchService {
  getUrl: String = './../assets/promotionList.json';
  subject: BehaviorSubject<Promotion[]> = new BehaviorSubject([]); // initialize with an empty response[]
  subjectAsObservable;
   someResult;
   promoList:Promotion[];
  constructor(private http: HttpClient) {
    this.getPromoList();
    console.log("after first");
    this.getPromoValues();
    console.log("after second call");
  }

    getPromoList(){
    // by default it emits a response of Json and hence Observabpe<PromotionList>
    // throws an error
    this.someResult = this.http.get(`${this.getUrl}`);
    console.log("before map"+<Observable<Promotion[]>> this.someResult);
    return (<Observable<Promotion[]>> this.someResult);
    //console.log("first subsriber"+JSON.stringify (this.someResult);

  }
    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
        });
}