Reputation: 933
new to Typescript and trying to get my head around it.
the following is the code that basically generates three random numbers and i use those to select random objects from json.
@Injectable()
export class TrackService {
public drawn :number[]=[];
constructor(private http: Http) {
}
public getRandomTrack(): Observable<Track[]> {
this.generateRandomNumbers();
console.log(this.drawn); //this.drawn is available here
return this.http
.get(API_ENDPOINT)
.map(this.extractRandomData);
}
public extractRandomData(res: Response) {
let body = res.json();
console.log(this.drawn); //undefined here
var randomTrack = [];
for(var i=0;i<this.drawn.length; i++){
randomTrack.push(body.results[this.drawn[i]]);
}
return randomTrack;
}
private generateRandomNumbers(){
var available = [];
for (var i = 1; i<= 55; i++) {
available.push(i);
}
for (var i = 0; i <3; i++) {
var random = Math.floor((Math.random() * available.length));
this.drawn.push(available[random]);
available.splice(random, 1);
}
return this.drawn;
}
as you see inside extractRandomData this.drawn is undefined, how do i pass the this.drawn into that function so i can access that array.
Please help.
Upvotes: 1
Views: 90
Reputation: 185
You can use any of the above answers. Both are right. Refer this link for more info this is undefined in map
Sample code
public getRandomTrack(){
this.generateRandomNumbers();
console.log(this.drawn);
[1,2].map(this.extractData,this); //Pass this as argument
[1,2].map(data => { // Arrow function
console.log(this.drawn);
}
extractData(val : any){
console.log(val);
console.log(this.drawn);
}
Upvotes: 0
Reputation: 5889
Drawn array is global in your service so you can access it whenever you want inside service, but your problem is in the map call, you should call like below:
return this.http.get(API_ENDPOINT)
.map(responseData => this.extractRandomData(responseData));
Upvotes: 1
Reputation: 933
I got it working by adding this at the end
https://www.tutorialspoint.com/typescript/typescript_array_map.htm
public getRandomTrack(): Observable<Track[]> {
this.generateRandomNumbers();
console.log(this.drawn);
return this.http
.get(API_ENDPOINT)
.map(this.extractRandomData,this);
}
thoughts on how good or bad is this?
Upvotes: 1
Reputation: 105449
You have to bind the context:
public getRandomTrack(): Observable<Track[]> {
this.generateRandomNumbers();
console.log(this.drawn); //this.drawn is available here
return this.http
.get(API_ENDPOINT)
.map((v) => { this.extractRandomData(v) });
}
See “this” cannot be used in typescript function (Angular) for more details.
Upvotes: 1