Search code examples
angularhttpserviceangular5injectable

Can't display data coming from service method into component


Still working on my Angular 5 - PHP project.

I want to put all my http methods inside a single file called api, and call any method I want by just importing it into the desired component. I don't know if it's good to work like that or not.

Anyway, here is my service called 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);
        }
      )
    }
}

And I imported it in 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 { }

And then I injected it in my component:

constructor(private fb: FormBuilder, private api: Api){

}

Which is here api: Api.

Now, I called the method that I want to use inside ngOnInit():

ngOnInit(){
    this.api.getPartnersName();
}

The problem is that is I am seeing the data at the console properly:

enter image description here

But can't display them on screen:

<div class="row center-block">
    <div class="col-sm-4" *ngFor="let datas of data;">
      {{datas.partner_name}}
    </div>
</div>

Solution

  • Your data is defined in the service, but you want it to use in the component. Actually you need to remove the subscribe part from the service's http call implementation and move it into the component.

    Service

    getPartnersName(){
        return this.http.get('http://aff.local/getPartners.php')
                        .map((response: Response) => response.json());      
    }
    

    Component

    ngOnInit(){
        this.api.getPartnersName().subscribe(data => this.data = data);
    }
    

    Also one note, with Angular 4.3 and upper, Http is deprecated, you can read about HttpClient