[英]Angular5: Return HttpClient response from a service to a Component?
I currently learning Angular 5 and I'm having difficulty on passing data from a service to a component. 我目前正在学习Angular 5,在将数据从服务传递到组件方面遇到困难。 I'm integrating this to wordpress..
我正在将其集成到wordpress中。
here's my current code: 这是我当前的代码:
orderers.component.ts 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 ? 我如何才能将get_user()转移到服务并返回数据并将其传递到组件中? Thanks .. :)
谢谢 .. :)
Step 1 Create your service and place your function inside 第1步创建服务并将功能放入其中
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 步骤2将服务注入到构造函数中后,在组件中调用您的服务
get_users() {
this.nameOfService.get_users_from_service().subscribe(data => {
this.orderers = data;
},
error => {
// Do something with error
}
}
First create service and copy your get_users() function. 首先创建服务并复制您的get_users()函数。 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.
每个http请求都返回一个类型为Observable的对象,这是包含subscribe()函数的对象,您需要在get_users()函数中将其返回。 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. 之后,您需要将其注入到组件中,就像注入HttpClient一样,并订阅get_users()函数。
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 顺便说一下,在angular.io上有很棒的例子https://angular.io/tutorial/toh-pt4
hope this was helpful 希望这会有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.