简体   繁体   English

如果我从组件调用,为什么角度服务数据未定义

[英]Why angular Service data is get undefined if I call from component

I am Using JSONPlace holder Fake API for fetching data.我正在使用 JSONPlace holder Fake API 来获取数据。 I am getting the api data in service but if I call that service from my app component I am getting undefined why this is my code我正在获取服务中的 api 数据,但是如果我从我的应用程序组件调用该服务,我将undefined为什么这是我的代码

My Service.ts is我的 Service.ts 是

import { Injectable } from '@angular/core';
import { Http, URLSearchParams, Response, RequestOptions, Headers } from '@angular/http';
import 'rxjs/RX';
import 'rxjs/add/operator/map';
@Injectable()
export class Service {
    apiRoot: string = 'https://jsonplaceholder.typicode.com/comments?' 
    postId = 1;
    data;
    constructor(private _http: Http) {
        this._http.get(this.apiRoot).subscribe((data) => {
            this.data = data.json();
        });
    }
    init() {
        return this.data;
    }

}

My component code is我的组件代码是

import { Component, OnInit } from '@angular/core'; import { InfiniteService } from './infinite.service'; //import all rxjs/Rx opeartor  import 'rxjs/add/operator/map';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit {
    data;
    constructor(private _infinteService: InfiniteService) {
        this.data = this._infinteService.init();
        console.log(this.data);
    }

    GetPosition($event) {
        if ($event == 'Bottom') {
            console.log($event);
        }
        else {
            console.log($event);
        }
    }
    ngOnInit() { }

}

why I am not able to get service data in component?为什么我无法在组件中获取服务数据?

Because HTTP its async function!因为 HTTP 它的异步功能! I recommend to use HttpClient, so you don't need to use map function!我推荐使用HttpClient,所以你不需要使用map函数! You can try that你可以试试

getData(): Observable<any> {
 return this._http.get(this.apiRoot)
}

And you just call him in component like that你就这样在组件中调用他

this._infinteService.getData().subscribe(
 data => console.log(data)
)

You need to return an Observable, and then you can use subscribe to call request.您需要返回一个 Observable,然后您可以使用 subscribe 来调用请求。 Try that and tell if worked!试试看,看看是否有效! Thanks谢谢

Make following changes in your code.在您的代码中进行以下更改。

Service :服务 :

constructor(private _http: Http) {
}
init() {
    return this._http.get(this.apiRoot);
}

Component :成分 :

constructor(private _infinteService: InfiniteService) {
    this._infinteService.init().subscribe((data) => {
        this.data = data;
        console.log(this.data);
    });
}

You need to use .subscribe in component call.您需要在组件调用中使用.subscribe

You don't need the .json() on your data object.您不需要数据对象上的.json() As of Angular4 the default responseType is JSON and the response data is already parsed for us.从 Angular4 开始,默认的 responseType 是 JSON,并且已经为我们解析了响应数据。

You should return the Observable from your service and subscribe to it in your component.您应该从您的服务返回Observable并在您的组件中订阅它。

The reason for this occur is it will take some time to get the response from the server.发生这种情况的原因是需要一些时间才能从服务器获得响应。 So we can set it in promises.所以我们可以在promise中设置它。 use the following command to get data in promises.使用以下命令获取 promise 中的数据。

 this._customerService.getCustomers().subscribe(data => this.customers = data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我在组件 Angular 8 中调用服务未定义 - I get undefined from calling a service in a component Angular 8 Angular从API调用返回的数据为[Object Object],但在组件中未定义 - Angular returns data from an API call as [Object Object], but undefined in the component Angular 6如何获取从组件到服务的方法调用状态? - Angular 6 How to get status of method call from Component to Service? 如何调用组件的get function from angular服务? - How to call the get function from angular service to a component? 为什么父组件能够从Angular服务获取Observable类型数据,但父组件却无法将数据传递给子组件? - Why is the parent component able to get Observable type data from Angular service but the parent is unable to pass the data to the child component? 我该如何从角度组件侦听服务中的http调用? - How do I listen to a http call in a service from a component in angular? 如何在Angular中从Service到Component调用函数? - How do I call a function from Service to Component in Angular? 为什么 Angular 中未定义订阅后从服务获取数据? - Why the data is gotten from service after subscribe is undefined in Angular? 从服务到组件的角度数据 - Angular data from service to component 在Angular 4中需要从服务到组件获取大量数据 - Need to get large chunk of data from service to component in Angular 4
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM