【问题标题】:Angular5: Return HttpClient response from a service to a Component?Angular5:将 HttpClient 响应从服务返回到组件?
【发布时间】:2017-11-27 09:05:56
【问题描述】:

我目前正在学习 Angular 5,但在将数据从服务传递到组件时遇到了困难。我正在将它集成到 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() 传输到服务并返回数据并将其传递到组件中? 谢谢.. :)

【问题讨论】:

标签: angular web


【解决方案1】:

首先创建服务并复制您的 get_users() 函数。 每个 http 请求都会返回一个 Observable 类型的 Object,这是包含 subscribe() 函数的对象,您需要在 get_users() 函数中返回它。 类似:

    @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');
    }
}

现在在您的模块中,您需要在提供者下列出此服务

@NgModule({
  imports: [...],
  declarations: [...],
  providers: [SomeNameService]
})

之后,您需要像注入 HttpClient 一样将其注入到您的组件中,并订阅您的 get_users() 函数。

constructor(private someService:SomeNameService) { }
ngOnInit(){
 this.someService.get_users().subscribe(data=>{
    this.orderers = data;
  });
}

顺便说一句,angular.io https://angular.io/tutorial/toh-pt4 上有很好的例子

希望对你有帮助

【讨论】:

    【解决方案2】:

    第 1 步 创建您的服务并将您的功能放入其中

    get_users_from_service(): Observable<any> {   
       return this.http.get(...)     // You can also try to catch any exception here
    }
    

    第 2 步 在构造函数中注入后在组件中调用你的服务

    get_users() {
       this.nameOfService.get_users_from_service().subscribe(data => {
          this.orderers = data;
       },
       error => {
           // Do something with error
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多