我目前正在学习Angular 5,并且在将数据从服务传递到组件方面遇到困难.我正在将其集成到wordpress中.
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..
这是我当前的代码: orderersponent.ts
import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Component({ selector: 'app-orderer', templateUrl: './ordererponent.html', styleUrls: ['./ordererponent.css'] }) export class OrdererComponent implements OnInit { o_manual:boolean = false; orderers = []; constructor(private http:HttpClient) { } ngOnInit() { this.get_users(); } get_users() { this.http.get('angular5.localhost/wp-admin/admin-ajax.php?action=orderers').subscribe( data => { this.orderers = data; } } }如何将get_user()转移到服务并返回数据并将其传递到组件中?谢谢..:)
how can i transfer get_user() to a service and return the data and pass it in the component ? Thanks .. :)
推荐答案首先创建服务并复制您的get_users()函数.每个http请求都返回一个类型为Observable的对象,这是包含subscribe()函数的对象,您需要在get_users()函数中将其返回.像这样的东西:
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('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] })之后,您需要将其注入到组件中,就像注入HttpClient一样,并订阅get_users()函数.
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; }); }顺便说一下,有关angular.io的例子很多. angular.io/tutorial/toh-pt4
by the way there are great examples on angular.io angular.io/tutorial/toh-pt4
希望这很有帮助
更多推荐
Angular5:将HttpClient响应从服务返回到组件?
发布评论