将返回的对象分配给客户端角度变量时出错

时间:2017-04-18 12:54:23

标签: angular exception components

我从服务器返回一个对象,当我试图将对象分配给角度组件对象中的变量时,我接收到异常。有人知道我错过了什么吗?

产品component.ts

import { Component, OnInit } from '@angular/core';
import { Product } from './product';
import { ProductsService } from './products.service';
import { ActivatedRoute, Params }   from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/map';

@Component({
  selector: 'product',
  templateUrl: './app/products/product.component.html'
})
export class ProductComponent implements OnInit {
    data: Product;

    constructor(private productSrv: ProductsService, 
                private route: ActivatedRoute) {}

    ngOnInit() {
        this.route.params.map( params => params['id'] ).subscribe(
            id => { 
                if (id)
                    this.productSrv.obtainProduct(+id).subscribe(
                            product => {
                                console.log(product);
                                this.data = <Product>product;
                            },
                            error => console.log(error));
                else 
                    this.data = <Product> {
                            id: 0,
                            name: '',
                            code: ''
                        };
           },
           error => console.log(error));
    }
}

产品-service.ts

import { Product } from './product';
import { PagingDetails } from './paging-details';
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

@Injectable()
export class ProductsService {

    constructor(private http: Http) { }

    obtainProduct(id: number): Observable<Product> {
        return this.http.get('/srv/product/' + id)
                        .map(this.extractData2)
                        .catch(this.handleError);
    }

    private extractData2( res: Response ): Product {
        let body = res.json();
        console.log(body);
        return <Product> (body || {});
    }

    private handleError( error: Response | any ) {
        // In a real world app, you might use a remote logging infrastructure
        let errMsg: string;
        if ( error instanceof Response ) {
            const body = error.json() || '';
            const err = body.error || JSON.stringify( body );
            errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
        } else {
            errMsg = error.message ? error.message : error.toString();
        }
        console.error( errMsg );
        return Observable.throw( errMsg );
    }
}

product.ts

export interface Product {
    id: number;
    name: string;
    code: string;
}

异常 Exception image

1 个答案:

答案 0 :(得分:0)

我设法重现了这个问题,所以在Firefox中,如果你不保护null / undefined值,就会抛出co.错误,在这种情况下,co.datadata 1}}未定义。您可能正在尝试在模板中使用它,例如

<div>{{data.code}}</div>

并且在呈现模板时,数据为undefined。您可以使用模板中的安全导航操作符来解决此问题:

<div>{{data?.code}}</div>

...或*ngIf。更多信息:Cannot read property "totalPrice" of undefined

解决此问题后,您将在控制台中获得undefined。问题是订阅中的转换:

.subscribe(product => {
    console.log(product);
    this.data = <Product>product; // here
}

这似乎导致data成为undefined。删除广告投放,因为您已将data标记为Product类型。因此,将其更改为:

.subscribe(product => {
    console.log(product);
    this.data = product; // here
}

所以上面应该解决你的问题。即使您在订阅中进行了更改,因此data也不会被定义,您必须使用例如模板中的安全导航操作符来保护空值/未定义值,因为http请求是异步的,并且呈现时间模板data将是未定义的。