Angular5:将HttpClient响应从服务返回到组件?

编程入门 行业动态 更新时间:2024-10-11 21:29:58
本文介绍了Angular5:将HttpClient响应从服务返回到组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在学习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响应从服务返回到组件?

本文发布于:2023-11-10 07:08:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574693.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组件   HttpClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!