【问题标题】:Angular2 reading JSONAngular2 读取 JSON
【发布时间】:2016-10-07 19:31:15
【问题描述】:

对于UsersController,我有以下GET 方法

public IEnumerable<object> Get()
{
    var con = _context.Database.GetDbConnection();
    var cmd = con.CreateCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "sp_Users";
    cmd.Parameters.Add(new SqlParameter("@Command", SqlDbType.VarChar) { Value = "GetUsers" });

    var retObject = new List<dynamic>();
    con.Open();
    using (var dataReader = cmd.ExecuteReader())
    {
        while (dataReader.Read())
        {
            var dataRow = new ExpandoObject() as IDictionary<string, object>;
            for (var iFiled = 0; iFiled < dataReader.FieldCount; iFiled++)
                dataRow.Add(
                    dataReader.GetName(iFiled),
                    dataReader.IsDBNull(iFiled) ? null : dataReader[iFiled] // use null instead of {}
                );

            retObject.Add((ExpandoObject)dataRow);
        }
    }
    return retObject;
}

我在 postman 中对其进行了测试,结果完美返回:

[{"UserID": 1, "UserName": "foo"}, {"UserID": 2, "UserName": "bar"}]

现在我想用angular2 显示它们,所以我编写了一个服务user.service.ts

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

@Injectable()
export class UsersService {
    student: any;
    constructor(private http: Http) { }

    getUsers() {
        return this.http.get('api/users')
            .map((res: Response) => <string[]>res.json()); 
    }
}

home.component.ts 我有:

ngOnInit() {
    this.usersService.getUsers()
        .subscribe(users=> this.users = users);
    console.log(this.users);
}

但我收到以下错误:

core.umd.js:3462 EXCEPTION: Unexpected token < in JSON at position 0ErrorHandler.handleError @ core.umd.js:3462next @ core.umd.js:6924schedulerFn @ core.umd.js:6172SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238SafeSubscriber.next @ Subscriber.ts:190Subscriber._next @ Subscriber.ts:135Subscriber.next @ Subscriber.ts:95Subject.next @ Subject.ts:61EventEmitter.emit @ core.umd.js:6164onError @ core.umd.js:6388onHandleError @ core.umd.js:6263ZoneDelegate.handleError @ zone.js:207Zone.runTask @ zone.js:139ZoneTask.invoke @ zone.js:304
core.umd.js:3467 ORIGINAL STACKTRACE:ErrorHandler.handleError @ core.umd.js:3467next @ core.umd.js:6924schedulerFn @ core.umd.js:6172SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238SafeSubscriber.next @ Subscriber.ts:190Subscriber._next @ Subscriber.ts:135Subscriber.next @ Subscriber.ts:95Subject.next @ Subject.ts:61EventEmitter.emit @ core.umd.js:6164onError @ core.umd.js:6388onHandleError @ core.umd.js:6263ZoneDelegate.handleError @ zone.js:207Zone.runTask @ zone.js:139ZoneTask.invoke @ zone.js:304
core.umd.js:3468 SyntaxError: Unexpected token < in JSON at position 0
    at Function.Json.parse (http.umd.js:188)
    at Response.Body.json (http.umd.js:1166)
    at MapSubscriber.eval [as project] (character.service.ts:11)
    at MapSubscriber._next (map.ts:79)
    at MapSubscriber.Subscriber.next (Subscriber.ts:95)
    at XMLHttpRequest.onLoad (http.umd.js:1497)
    at ZoneDelegate.invokeTask (zone.js:236)
    at Object.onInvokeTask (core.umd.js:6233)
    at ZoneDelegate.invokeTask (zone.js:235)
    at Zone.runTask (zone.js:136)ErrorHandler.handleError @ core.umd.js:3468next @ core.umd.js:6924schedulerFn @ core.umd.js:6172SafeSubscriber.__tryOrUnsub @ Subscriber.ts:238SafeSubscriber.next @ Subscriber.ts:190Subscriber._next @ Subscriber.ts:135Subscriber.next @ Subscriber.ts:95Subject.next @ Subject.ts:61EventEmitter.emit @ core.umd.js:6164onError @ core.umd.js:6388onHandleError @ core.umd.js:6263ZoneDelegate.handleError @ zone.js:207Zone.runTask @ zone.js:139ZoneTask.invoke @ zone.js:304
Subscriber.ts:241 Uncaught SyntaxError: Unexpected token < in JSON at position 0

【问题讨论】:

  • Unexpected token &lt; in JSON at position 0 - 你的 json 不是 json。还有别的东西。 &lt; 暗示这是一个 html 错误或什么的。&lt;p&gt;Warning:blahblalblah&lt;/p&gt;{"json":"here"} 不是有效的 json...
  • 如何在 Angular 中调试它?因为当我转到localhost:5000/api/users/ 的应用程序时,我得到一个 JSON 格式的文本,postman 也显示了同样的内容。
  • 在原始返回数据到达 json 解析器之前捕获/输出它。
  • 您应该能够在您使用的任何浏览器的开发人员工具中使用网络选项卡来查看 http 请求和响应。我的猜测是它请求的 URL 不是正确的 - 可能是您与 api 的相对 URL 的问题?

标签: c# json http angular angular2-services


【解决方案1】:

我修复了以下内容:

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

@Injectable()
export class UsersService {

    constructor(private http: Http) { }

    getUsers(): Observable<any[]> {
        return this.http.get('api/users')
                    .map(this.extractData)
                    .catch(this.handleError);
        }
        private extractData(res: Response) {
            console.log(res);
            let body = res.json();
            return body.data || { };
        }
        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);
        }
}

【讨论】:

    猜你喜欢
    • 2016-06-12
    • 1970-01-01
    • 2016-07-28
    • 2017-06-26
    • 1970-01-01
    • 2017-06-10
    • 2017-05-13
    • 2017-07-23
    • 1970-01-01
    相关资源
    最近更新 更多