【发布时间】:2018-01-30 12:34:33
【问题描述】:
我有一个角度组件。我从 API 获取数据并实例化一个新对象以创建地图。但我无法访问订阅函数之外的变量。我也无法访问我的方法。
maps.service.ts
这部分,获取数据表单api
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Injectable()
export class MapsService {
constructor(private http: HttpClient) { }
getMap(params) {
console.log('Service', params);
return this.http.get('/api/posts/' + params.id);
}
}
map.component.ts 这里是我以后用google建地图的地方
import { Component, OnInit } from '@angular/core';
import {MapsService} from '../maps.service';
import {ActivatedRoute} from '@angular/router';
import {MapPath} from '../map-path';
@Component({
selector: 'app-maps',
templateUrl: './maps.component.html',
styleUrls: ['./maps.component.css']
})
export class MapsComponent implements OnInit {
results: any;
params: {};
test: any;
constructor(
private mapsService: MapsService,
private route: ActivatedRoute,
) { }
ngOnInit() {
this.route.params.subscribe( params => {
this.params = params;
});
this.mapsService.getMap(this.params).subscribe(
data => {
this.results = data;
this.test = new MapPath(data, 'test');
},
err => {
console.log('Error occured', err);
});
console.log('this.test', this.test.getX());
console.log('this.results', this.results);
}
}
map-path.ts 这里从geoJSON获取不同的属性
export class MapPath {
test: string;
constructor(path: any, test: string) {
this.test = test;
console.log('Path', path);
console.log('test', test);
}
getX() {
return this.test;
}
}
谢谢。
【问题讨论】:
标签: javascript angular