看这个之前,你要确保你的教程没错,能跑起来。最近好多人都遇到http请求问题。不知道怎么跟后台接口对接。首先,在我们的英雄指南教程里面,有个模拟的假数据,我们不需要导入他,那么在app.module.ts里面,我们需要把导入的angular-in-memory-web-api注释掉或者删掉,同时需要在下面@NgModule里面的imports:里找到如下代码删掉即可:InMemoryWebApiModule.forRoot(InMemoryDataService),然后我们需要在hero.service.ts里面更改如下:
@Injectable() export class HeroService { private heroesUrl = 'http://10.1.1.80:8080/test1'; (此处为后台接口,更改为贵公司接口即可。) }这样你的英雄列表是从后台获取的了,而后,我们也可以 在hero-detail.component.html里加个测试按钮,在 hero-detail.component.ts里面写个点击事件测试:
<button (click)="test()">test</button>
test(): void{ this.http.get('http://10.1.1.80:8080/test1') .toPromise().then((response) => { console.log(response.json()); }); }
这里需要注意的是,你需要在hero-detail.component.ts里面导入如下:
在 constructor里面需要写:private http: Http。这样就OK了。。import { Http ,Response} from '@angular/http'; import 'rxjs/add/operator/toPromise';
我还写了个函数测试调用= =:
test2():void{ alert("test3"); } kf():void{ alert("777"); this.test2(); } test(): void{ this.http.get('http://10.1.1.80:8080/test1') this.kf(); }