【问题标题】:Angular2 consuming service that makes HTTP call in component method在组件方法中进行 HTTP 调用的 Angular2 消费服务
【发布时间】:2016-06-26 19:55:12
【问题描述】:

我正在学习Angular2并且有以下疑问:

我编写了一个发出 HTTP 请求并获取数据的服务。在我的组件中,我想要一个使用此服务的方法,并且在该组件的 HTML 模板上,我有一个 onClick 调用此方法的按钮。

我的服务:

import {Injectable} from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable }     from 'rxjs/Observable';

@Injectable()
export class HomeService{

    data: Object;
    loading: boolean;

    constructor(private http: Http){}

    public myUrl = 'http://jsonplaceholder.typicode.com/users';

    fetchData(): any {

        this.loading = true;
        this.http.request(this.myUrl)
          .subscribe(
            (res: Response) => {

            this.data=res.json();
            this.loading=false;

            return this.data;

          });
      }

}

我的组件:

import {Component} from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

import {HomeService} from './home.component.service';



@Component({

    selector:'home',
    templateUrl:'./app/Home/home.component.html',
    providers:[HomeService],
    directives: [ROUTER_DIRECTIVES]

})
export class Home {

    data: Object;

    constructor(){}

    getData(){

    }
}

我的模板:

<button type="button" (click)="getData()">Make Request</button>

<div *ngIf="loading">loading...</div>
      <pre>{{data}}</pre>

如何实现这个 getData() 方法?使用此类 HTTP 服务是否正确?

【问题讨论】:

    标签: angular


    【解决方案1】:

    注入服务然后使用它:

    export class Home {
    
     data: Object;
    
     constructor(private myService:HomeService){}
    
     getData(){
       this.data = this.myService.fetchData();
     }
    }
    

    【讨论】:

    • 执行此操作后,没有错误,但屏幕上没有打印任何内容。我在 getData() 里面做了 console.log(this.data) 这给了我未定义的。服务本身有什么问题吗?
    • 解决了!在服务的构造函数中移动了 HTTp 调用,并且 fetchData() 简单地返回 this.data
    猜你喜欢
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-12
    • 2017-04-25
    • 2018-03-08
    • 2017-04-13
    • 1970-01-01
    • 2016-10-13
    相关资源
    最近更新 更多