Angular5:将HttpClient响应从服务返回到组件? [英] Angular5: Return HttpClient response from a service to a Component?

查看:76
本文介绍了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..

这是我当前的代码:
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;
    }
} }

如何将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('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]
})

之后,您需要将其注入到组件中,就像注入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的例子很多. https://angular.io/tutorial/toh-pt4

by the way there are great examples on angular.io https://angular.io/tutorial/toh-pt4

希望这很有帮助

这篇关于Angular5:将HttpClient响应从服务返回到组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆