首页 > 解决方案 > Angular 4 Observable subscription can't access integer number to base2[0]

问题描述

In my component I am subscribing Observable method where I am getting a value (value type of number). I can convert it from number to bit using .toString(2) method. I want to access each bit separately. lets say base2= 101010. I want to access it like base2[0] (which wiil be 1).

    constructor(private service: serviceApi) {
    this.subscription = this.service.getStatus().subscribe(statusCode => {
      this.code = statusCode; // console.log(typeof this.code) : number 297
      this.base2 = (this.code).toString(2);  //console.log(this.base2) : 0100101001
      this.base2[1] // Can't to access

     });
    }

This is throwing error inside observable subscription method (in code above). If I just put same method only inside constructor without subscribes method (by hard coding number), It works like base[1] (1 is the position of binaray number)

标签: angularrxjs

解决方案


While using base2 in template try to check if base2 is set using *ngIf

<ng-container *ngIf="base2">  
    {{ base2[0]}}
</ng-container>

推荐阅读