【问题标题】:How I can see value of variable outside subscrib or Promise in Ionic 3我如何在 Ionic 3 中查看订阅或 Promise 之外的变量值
【发布时间】:2018-07-18 01:20:13
【问题描述】:

对不起我的英语。

我在尝试使用 subscribe 或 Promise 查看 api rest 的结果时遇到问题。

我有一个提供下一个代码的提供程序:

提供者:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';



@Injectable()
export class UserServiceProvider {

   path : string  = 'my_paht_remote';

  constructor(public http: HttpClient) {
    console.log('Hello UserServiceProvider Provider');
  }

  getUsers() {

    return this.http.get(this.path');

  }

  getList()
  {
    return new Promise ( resolve => {
      this.http.get(this.path).subscribe(
        data => {

          resolve(data);
        }, err => {
          console.error();
        }

      );


    } );
  }

}

现在,在文件 typeScript 中

--Imports
...
import { UserServiceProvider } from '../../providers/user-service/user-service';
...
export class CaicesPage {

users: any;
users2: any;
   ...
ionViewDidLoad()
  {
    this.showMap();  //This is a function for see Google Maps. 
  }

showMap()
  {
    //Here I can see the result of JSon File remote:

       this.userService.getUsers().subscribe(
        (data) => { // Success
          this.users = data['results'];   



        },
        (error) =>{
          console.error(error);
        }
      );

     console.info(this.users); // I see Undefined, Why ?

   //Whith the next form, Also can see the content File Json
   this.userService.getList().then(

      data => {

        this.users2=data['results'];


      }
    );

    console.info(this.users2); // I see Undefined, Why ?

   }


}

如何在订阅或 THEN 之外查看 var users 或 var users2 的值?

感谢合作

【问题讨论】:

    标签: typescript ionic-framework ionic3


    【解决方案1】:

    如果您在成功分支中显示变量,您会看到什么?您是否看到了一个值,以确认您的服务实际上返回了正确的值?例如

    showMap()
    {
    //Here I can see the result of JSon File remote:
    
       this.userService.getUsers().subscribe(
        (data) => { // Success
          this.users = data['results'];   
          console.info(this.users); <=============== HERE
    
    
        },
        (error) =>{
          console.error(error);
        }
      );
    

    您不会在原始位置看到日志的值,因为此代码在调用 subscribe 后立即执行,即在服务实际返回值之前。

    【讨论】:

    • 我看到了return的值;示例:{punto_pago:“Palocabildo-Enertolima”,方向:“CALLE 6 No 6-36 PRIMER PISO CENTRO”,tipo_aliado:“Punto de recaudo”,horario:“Lunes a viernes de 7:30 am a 12:30 pm y下午 1:30 到下午 5:00。萨巴多斯早上 7:30 到下午 5:00"}。但是,外部订阅 console.info(this.users);显示未定义
    • 您只有在订阅成功执行后才能访问this.users 的值。在您的原始代码中,事件顺序是: 1. 调用 getUsers() - 一个异步调用。 2. console.info(this.users) - 此时,this.users 仍未定义。 3. getUsers() 完成并且您的成功订阅执行。现在您可以访问this.users
    猜你喜欢
    • 1970-01-01
    • 2020-12-18
    • 1970-01-01
    • 2021-02-16
    • 2022-09-23
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 2020-05-18
    相关资源
    最近更新 更多