无法从Angular2中的应用程序组件访问服务

时间:2017-08-14 08:16:18

标签: angular

这是 data.ts 类,我已经定义了我想要访问的对象的变量:

export class Data {
  id : number;
  name : string;
}

然后我的 mock-data.ts 类,我将返回一个硬编码的对象数组:

import { Data } from './data';
import { Http,Headers,RequestOptions } from  '@angular/http';

export const DATAS : Data[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

console.log(DATAS);

我的 my-service.ts 类,我将返回一个Data []类型的Promise对象。(直到这里我恢复了我的对象)

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Headers,RequestOptions } from  '@angular/http';
import { Observable } from 'rxjs';
import { DATAS } from '../../app/mock-data';
import { Data } from '../../app/data';

/*
  Generated class for the MyServiceProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular DI.
*/
@Injectable()
export class MyServiceProvider {

  DATAS : Data[];

  openWebMwthod() : Promise<Data[]>{

    console.log("Here data is",DATAS);
    return Promise.resolve(DATAS);

  }

}

但是,在我从 app.component.ts 文件调用服务的最后一步中,我得到的对象未定义:

import { Component, OnDestroy  } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
//import { Subscription } from 'rxjs/Subscription';
import { HomePage } from '../pages/home/home';
import { MyServiceProvider } from '../providers/my-service/my-service';
import { Http,Headers,RequestOptions } from  '@angular/http';
import { Data } from './data';
import { OnInit } from '@angular/core';


@Component({
  templateUrl: 'app.html'
})
export class MyApp implements OnInit{
  rootPage:any = HomePage;
  datas : Data[];


  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, private myServiceProvider : MyServiceProvider) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();

    });
  }

 getData() : any{
   //console.log("Calling web service");
   this.myServiceProvider.openWebMwthod().then(datas => this.datas = datas);
   console.log("obj is",this.datas);
 }

   ngOnInit(): void {
     this.getData();
     console.log("Debo data:",this.getData());

  }

}

有人能说出我可能出错的地方吗?

2 个答案:

答案 0 :(得分:1)

您正在服务类中定义DATAS类参数,该参数将使用undefined值进行初始化。您正在从模拟对象中挟持正确的DATAS对象,但我认为它可能会被覆盖。

顺便说一句,在console.log解析之前,组件中的Promise第34行可能正在记录方式,因为承诺解析是异步的。因此,您应该使用then方法进行日志记录,以查看在promise中解析的值。

BTW v2,另一条console.log第39行未记录任何内容,因为getData未返回任何内容。

答案 1 :(得分:0)

这是工作解决方案:

<强> app.component.ts(节选)

 ngOnInit(){
     this.myServiceProvider.openWebMwthod()
         .subscribe((response)=>{
            this.datas = response;
            console.log("here Inside app component",this.datas);
            alert("here Inside app component"+this.datas);
        });   

  }

我-service.ts(节选)

openWebMwthod() : Observable<any>{


    let headers = new Headers(
        {
          'Content-Type': 'application/json',    
        }
      );

    let options = new RequestOptions({headers:headers});

    return this.http.get('https://jsonplaceholder.typicode.com/posts',options)
             .map( (res) => res.json())


  }