问题
I currently learning Angular 5 and I'm having difficulty on passing data from a service to a component. I'm integrating this to wordpress..
here's my current code:
orderers.component.ts
import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-orderer',
templateUrl: './orderer.component.html',
styleUrls: ['./orderer.component.css'] })
export class OrdererComponent implements OnInit {
o_manual:boolean = false;
orderers = [];
constructor(private http:HttpClient) { }
ngOnInit() {
this.get_users();
}
get_users() {
this.http.get('http://angular5.localhost/wp-admin/admin-ajax.php?action=orderers').subscribe( data => {
this.orderers = data;
}
} }
how can i transfer get_user() to a service and return the data and pass it in the component ? Thanks .. :)
回答1:
First create service and copy your get_users() function. Every http request return an Object of type Observable, this is the object that contains the subscribe() function, you need to return it in the get_users() function. something like :
@Injectable()
export class SomeNameService {
constructor(private http: HttpClient) {
}
get_users():Observable<any> {
return this.http.get('http://angular5.localhost/wp-admin/admin-ajax.php?action=orderers');
}
}
now in your Module you need to list this service under the providers
@NgModule({
imports: [...],
declarations: [...],
providers: [SomeNameService]
})
after that you need to inject it into your component just like you injected HttpClient, and subscribe to your get_users() function.
constructor(private someService:SomeNameService) { }
ngOnInit(){
this.someService.get_users().subscribe(data=>{
this.orderers = data;
});
}
by the way there are great examples on angular.io https://angular.io/tutorial/toh-pt4
hope this was helpful
回答2:
Step 1 Create your service and place your function inside
get_users_from_service(): Observable<any> {
return this.http.get(...) // You can also try to catch any exception here
}
Step 2 Call your service in the component after injecting it in the constructor
get_users() {
this.nameOfService.get_users_from_service().subscribe(data => {
this.orderers = data;
},
error => {
// Do something with error
}
}
来源:https://stackoverflow.com/questions/47507179/angular5-return-httpclient-response-from-a-service-to-a-component