对Typescript不熟悉并尝试着解决它。
以下是基本上生成三个随机数的代码,我使用它们从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;
}
正如你在extractRandomData里面看到的那样,this.drawn是未定义的,我如何将this.drawn传递给该函数,以便我可以访问该数组。
请帮忙。
答案 0 :(得分:1)
您必须绑定上下文:
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) });
}
参见“this” cannot be used in typescript function (Angular) 了解更多详情。
答案 1 :(得分:1)
我在最后添加了这个工作
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);
}
关于这个有多好或多坏的想法?
答案 2 :(得分:1)
绘制的数组在您的服务中是全局的,因此您可以在需要内部服务时访问它,但问题出在地图调用中,您应该如下调用:
return this.http.get(API_ENDPOINT)
.map(responseData => this.extractRandomData(responseData));
答案 3 :(得分:0)
您可以使用上述任何答案。两者都是对的。 有关详细信息,请参阅此链接this is undefined in map
示例代码
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);
}