仍在处理我的 Angular 5 - PHP 项目。
我想将我所有的 http 方法放在一个名为 api 的文件中,并通过将其导入所需的组件来调用我想要的任何方法。我不知道这样工作好不好。
无论如何,这是我的service
电话api.ts
:
import {Injectable} from '@angular/core';
import { Http, Response } from '@angular/http';
@Injectable()
export class Api{
public data: any = [];
constructor(private http: Http){ }
getPartnersName(){
this.http.get('http://aff.local/getPartners.php').subscribe(
(response: Response) =>{
this.data = response.json();
console.log(this.data);
//this.keys.push(this.data);
},
error =>{
console.log(error);
}
)
}
}
我将它导入app.module.ts
:
...//imports
...//Other imports
import { Api } from '../api/api';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
HttpModule
],
providers: [Api],
bootstrap: [AppComponent]
})
export class AppModule { }
然后我将它注入到我的组件中:
constructor(private fb: FormBuilder, private api: Api){
}
这是在这里api: Api
。
现在,我调用了我想在里面使用的方法ngOnInit()
:
ngOnInit(){
this.api.getPartnersName();
}
问题是我在控制台上正确地看到了数据:
但无法在屏幕上显示它们:
<div class="row center-block">
<div class="col-sm-4" *ngFor="let datas of data;">
{{datas.partner_name}}
</div>
</div>