我对angular2和打字稿有问题。我尝试获取数据 jsonp,但返回函数是可观察的,我需要 de 对象结果。我需要帮助。
在此处输入图像描述
帐户.ts
import { Component} from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import {AccountService} from '../../providers/account-service';
import { Observable } from 'rxjs/Rx';
@Component({
selector: 'page-account',
templateUrl: 'account.html',
providers: [AccountService]
})
export class AccountPage {
data: any;
listAccounts: any;
accounts: any;
constructor(public navCtrl: NavController, public navParams: NavParams, private AccountService: AccountService) {
this.accounts = this.getAccountsResult();
}
getAccountsResult() {
return this.AccountService.retrieveAccounts();
}
getAccountsResultDebug() {
console.log(this.AccountService.retrieveAccounts());
}
}
accounts-service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions, Jsonp } from '@angular/http';
import 'rxjs/Rx';
/*
Generated class for the AccountService provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class AccountService {
/**
* Variaveis globais
**/
data: Array<AccountService>;
token: string;
url: string;
param: string;
result: any;
constructor(private http: Http, private jsonp: Jsonp) {
this.http = http;
this.jsonp = jsonp;
this.token = 'tokenofapp'
this.url = 'urlofapp'
}
/**
* PROGRAMADOR: Débora Gonçalves
* DATA: 23/01/2017
* OBJETIVO: Recuperando dados da API accounts
**/
retrieveAccounts() {
// variavel para enviar os headers
let headers = new Headers();
//definindo valores no array headers
headers.append('x-access-key', this.token);
headers.append('Content-Type', 'application/jsonp');
// definindo o requestoptions com os parametros do headers
let options = new RequestOptions({
headers: headers
});
//executando requisição da url
//return this.jsonp.get(this.url, options).map(res => res.json());
// .subscribe(
// data => this.result = [data]
//);
return this.jsonp.get(this.url, options).map(res => res.json());
}
}
帐户页面
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>Contas</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item outline *ngFor="let i of accounts.result" (click)="openPage($event, 1, DetailsAccountPage)">
<p>a</p>{{i}}
<p *ngFor="let f of i" strong>Nome do fulano {{f}}</p>
</button>
<button ion-item outline>
<p strong>Nome do fulano</p>
<div class="item-note" item-right>
</div>
</button>
<button ion-item outline (click)="getAccountsResultDebug()">
<p strong>Nome do fulano</p>
<div class="item-note" item-right>
</div>
</button>
</ion-list>
</ion-content>
您需要在组件中订阅 Angular 2 服务。
跟随https://scotch.io/tutorials/angular-2-http-requests-with-observables
这需要在您的组件中。无论您在哪里调用您的服务。.subscribe( 数据 => 这个。结果 = [数据] );