Angular2 HTTP 使用 observables 订阅显示未定义的数据 [英] Angular2 HTTP using observables subscribe showing data undefined

查看:17
本文介绍了Angular2 HTTP 使用 observables 订阅显示未定义的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我做错了什么,但不知何故我无法读取数据,尽管数据来自服务器作为响应,甚至数据在我放入时在服务 extractData 方法中显示控制台,但在订阅功能内的组件中,它给了我未定义的信息.帮助我做错了什么,我假设这是异步的问题,但是,我不知道如何正确.任何帮助将是可观的.提前谢谢

I don't know what I'm doing wrong but somehow i'm not able to read data, though the data is coming from server in response and even the data is getting showed inside service extractData method when I'm putting the console but in component inside subscribe function it is giving me undefined. Help me what I'm doing wrong, what I'm assuming is that this is the problem of async but, I have no idea how correct it. Any help will be appreciable. Thanx in advance

Component.ts

import { Component, Input, OnInit } from '@angular/core';
import {AdminService} from './admin.service';
import {logistics} from '../shared/model/logistics';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import { Observable }     from 'rxjs/Observable';
import {Response } from '@angular/http';
@Component({
    moduleId:module.id,
    selector: 'admin',
    templateUrl: 'admin.component.html',
    styleUrls:['admin.component.css'],
    providers:[AdminService]
})

export class AdminComponent implements OnInit{
   @Input() public allocatedAssetsList: logistics[];


    mode = 'Observable';
    public errorMsg = '';
    constructor(private adminService: AdminService) {

    }

    ngOnInit(){
        this.listByEmpId("123");

    }

    listByEmpId(empId:string){

        this.adminService.getAllocatedAssets(empId).subscribe(
        res => this.allocatedAssetsList = res,
        error =>  this.errorMessage = <any>error);
    }
}

Service.ts

import { Injectable }     from '@angular/core';
import { Http, Response } from '@angular/http';
import { Hero }           from './hero';
import { Observable }     from 'rxjs/Observable';
import { Headers, RequestOptions } from '@angular/http';
import {logistics} from '../shared/model/logistics';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';


@Injectable()
export class AdminService {
    constructor (private http: Http) {}
    private listAssetsURL = '/api/logistics/list/';  // URL to web API

    private extractData(res: Response) {
        let body = res.json();
        return body || { };
    }

    private handleError (error: any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }

    getAllocatedAssets (empId: string): Observable<logistics[]> {

        this.listAssetsURL+= empId;
        //let body = JSON.stringify({ empId });
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        return this.http.get(this.listAssetsURL)
            .map(this.extractData)
            .catch(this.handleError);
    }
}

推荐答案

listByEmpId(empId:string){

    this.adminService.getAllocatedAssets(empId).subscribe(
    res => {
      this.allocatedAssetsList = res;
      console.log(this.allocatedAssetsList);
    },
    error =>  this.errorMessage = <any>error);
}

这篇关于Angular2 HTTP 使用 observables 订阅显示未定义的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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