Angular 2 SyntaxError:意外的令牌&lt;在JSON位于JSON.parse的位置0(<anonymous>)

时间:2017-11-08 22:14:39

标签: angular typescript asp.net-web-api

我从Visual Studio中的Angular2组件服务调用Web API,但我不断收到错误&#34;意外令牌&lt;在JSON的位置0,在JSON.parse()&#34;。

ComponentService:

       import { Injectable } from '@angular/core';
       import {Http, Response } from '@angular/http';
       import { IData } from '../Common/details';
       import { Observable } from 'rxjs/Observable';
       import 'rxjs/add/operator/map';

       @Injectable()  
       export class AniversaryService {
         constructor(private _http:Http) { }
         getImages(): Observable<IData[]> {
                return this._http.get("/api/ImageService/Details")
                .map((response: Response) => <IData[]>response.json()      
                };
        }

和相应的组件是:

    import { Component, OnInit } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser';
    import { IData } from '../Common/details';
    import { AniversaryService } from './Aniversary.service';

    @Component({
    selector: 'my-AniversaryComponent',
    providers: [AniversaryService]
    })

    export class AniversaryComponent implements OnInit {
       data: IData[];
       constructor(private _aniversaryservice: AniversaryService) { }
       ngOnInit() {
       this._aniversaryservice.getImages().subscribe((details) => this.data 
       =details); 
       }
     }

    }

这些是网络标题和我的响应的图像(响应是在Javascript中):

In Developer tool the network Headers image:

and my response is in Javascript

有时我的状态代码显示200 ok和内容类型(在响应标题中):application / javascript

请帮我解决这个问题。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

标题没有用,数据也是如此。但错误信息很明确:您认为应该是JSON,以&#34;&lt;&#34;作为第一个角色,JSON并没有以&#34;&lt;&#34;开头。很可能你收到的是html或xml。

答案 1 :(得分:0)

-I重新创建了我的组件服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import { IDetails } from '../share/Details';

    @Injectable()
    export class AniversaryService {
        private url = 'http://localhost:60975/api/ImageService';
        constructor(private _http: HttpClient) { }
        getDetails(): Observable<IDetails[]> {
            return this._http.get<IDetails[]>(this.url)
                .do(data => console.log(JSON.stringify(data)))
                .catch(this.handleError);
        }
        private handleError(err: HttpErrorResponse) {
            console.log(err.message);
            return Observable.throw(err.message);
        }
    }

现在它正在接受数据而没有任何错误。