我写的代码是在angular2中对php web-service进行http调用。控制台中没有错误,但是没有显示o / p。 我的代码如下:
hero.service.ts
import { Hero } from './hero';
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { HEROES } from './mock-heroes';
@Injectable()
export class HeroService {
private heroesUrl = 'http://localhost/ex/ex1.php';
constructor(private http: Http) {}
getHeroes(): Promise<Hero[]> {
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
ex1.php
<?php
header("Access-Control-Allow-Origin: *");
$arr = array(
array("id" => 1, "name" => "Rajneesh"),
array("id" => 2, "name" => "Rahul")
);
echo json_encode($arr);exit;
?>
app.component.ts
import { Component, OnInit } from '@angular/core';
import { HeroService } from './hero.service';
import { Hero } from './hero';
@Component({
selector: 'my-app',
template: `<h1>ss</h1>
<div *ngFor="let hero of heroes">
{{hero.name}}
</div>
`,
})
export class AppComponent implements OnInit {
heroes: Hero[];
constructor(private heroService: HeroService) {}
ngOnInit(): void {
this.getHeroes();
}
getHeroes(): void {
this.heroService.getHeroes().then(heroes => this.heroes =
heroes);
}
}
非常感谢任何形式的帮助