【问题标题】:IONIC API UndefinedIONIC API 未定义
【发布时间】:2020-04-30 03:24:39
【问题描述】:

我有一个带有 CORDOVAIONIC APP。我只想从 URL GET a JSON

我创建了一个服务调用 rest.service.ts

rest.service.ts

import { Injectable } from '@angular/core';
import { HTTP } from '@ionic-native/http/ngx';

@Injectable({
  providedIn: 'root'
})
export class RestService {

  BASE_URL = 'http://whatever.....';

  constructor(public http: HTTP) {}

  getProjects() {

    const URL = this.BASE_URL + 'getProjects';

    this.http.get(URL, {}, { 'Content-Type': 'application/json' })
      .then(answer => {

        return JSON.parse(answer.data);

      })
      .catch(error => {
        console.log(error.status);
        console.log(error.error); // error message as string
        console.log(error.headers);
      });

  }

}

在这个文件中,我可以看到信息。如果我插入类似...

console.log(JSON.parse(answer.data));

我可以在 JSON 中随心所欲地查看结果。

问题是当我尝试在其他文件中使用此方法时...

otherpage.page.ts

import { Platform } from '@ionic/angular';
import { RestService } from './../rest.service';
import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-otherpage',
  templateUrl: './otheropage .page.html',
  styleUrls: ['./otherpage .page.scss']
})
export class OtherPage implements OnInit {

  projects;

  constructor(
    public platform: Platform,
    public rest: RestService,
  ) {


    this.projects = this.rest.getProjects();
    console.log(this.projects); // UNDEFINED

  }

  ngOnInit() { }

}

这里...this.projects... 未定义... ¿发生了什么?我试过platform.ready,插入ngOnInit.. . 没有任何效果。

【问题讨论】:

    标签: json angular api ionic-framework


    【解决方案1】:

    您需要修改服务并在您的页面订阅此服务。

     BASE_URL = 'http://whatever.....';
     getProjects() {
        const URL = this.BASE_URL + 'getProjects';
        return this.http.get(URL, {}, { 'Content-Type': 'application/json' });
      }
    

    在您的 page.ts 文件中订阅该服务 observable。

    this.rest.getProjects().subscribe((answer)=>{
        this.projects = JSON.parse(answer.data);
        console.log(this.projects); // here you get the json 
    },error=>{
        consoole.log(error)
    });
    

    注意:

    console.log(this.projects); // 不明确的 因为此行在 http observable 发送响应之前执行,所以您需要订阅该 http observable 才能获取 json。

    【讨论】:

    • 谢谢。只是 subscribe() 方法不存在。我使用了.then()。我只是想尽可能地简化我的 page.ts 文件,所以我没有考虑过。我只想在我的 Rest 文件中完成所有 API 工作。但它现在工作正常!谢谢
    猜你喜欢
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 2015-11-29
    • 2022-01-02
    • 2017-12-12
    • 2015-06-20
    • 1970-01-01
    相关资源
    最近更新 更多