mautrok mautrok - 3 months ago 133
TypeScript Question

initialize map in TypeScript

I have to understand this strange behavior

code



private map:Map<string,number>=new Map<string,number>();

callForFlower(cookie:string) : Observable<Map<string,number>>{
try{
this.url='https://flower.it/getFlower;
return this.http.get(this.url)
.map(this.extractFlower)
.catch(this.handleError);
}catch(err){
this.errMsgSubj.next(err)
}
}
extractFlower(){
this.addRose();
}
addRose(){
this.map.set("rose",0)
}


when I do map.set I get an exception


this.map is undefined


why? is there another way to initialize Map object in typescript?

Answer

If you want to use this in methods passed around like

    .map(this.extractFlower)
    .catch(this.handleError);

you should change it to

    .map(this.extractFlower.bind(this))
    .catch(this.handleError.bind(this));

or

    .map((param) => this.extractFlower(param))
    .catch((param) => this.handleError(param));

but this way you have to list all required parameters twice, therefore the first suggestion is usually the preferred one for this use case.