【问题标题】:Cannot access variable outside the subscription无法访问订阅之外的变量
【发布时间】:2018-01-30 12:34:33
【问题描述】:

我有一个角度组件。我从 API 获取数据并实例化一个新对象以创建地图。但我无法访问订阅函数之外的变量。我也无法访问我的方法。

ma​​ps.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);
    }
}

ma​​p.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);

     }

}

ma​​p-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


    【解决方案1】:

    您的问题是 Observables 是异步函数,这意味着您的订阅回调将在您的 this.mapsService.getMap 调用之后的 console.log 调用之后发生。

    Observables 的异步特性保证了这一点。

    您可以将控制台日志移动到订阅函数中,也可以创建另一个订阅。

    希望这会有所帮助。

    【讨论】:

    • 好的,谢谢,但是如何在订阅之外访问方法的类?像这样,我只能在里面访问我的方法...
    • 您必须等到数据可用。您的方法将可用,但只有在处理订阅后。
    • 在不了解您的完整规格的情况下,我无法进一步帮助您。也许您可以解释一下您的应用程序的用例流程是什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    相关资源
    最近更新 更多