【问题标题】:Angular4 TypeScript JsonReaderExceptionAngular4 TypeScript JsonReaderException
【发布时间】:2018-05-07 12:33:35
【问题描述】:

我有显示给用户的包含 1 条或多条记录的表。用户选择一个或多个复选框并提交,当表单提交时,数据库中的数据会更新。在那一刻,我来自代码调用 location.relaod();为了重新加载页面并显示正确的数据。

这是来自后端 web api 的代码:

[HttpGet]
public async Task<object> Get()
{
    var entries = await _entryRepository.GetEntriesByUserIdAsync(await GetUserId());

    var result = _mapper.Map<IEnumerable<Entries>, IEnumerable<EntryReponse>>(entries);

    return Ok(result);
}

这是调用 web api 的服务代码:

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { AuthService } from "./auth.service";
import { Entry } from "../models/entry";
import { Observable } from 'rxjs/Rx';

@Injectable()
export class EntryService
{
    private readonly API_URL = 'http://localhost:52841/api/entry/';
    constructor(private http: Http,
        private authService: AuthService) { }


    createEntry(id) {
        let headers = new Headers();
        headers.append('Authorization', "Bearer " + this.authService.token);

        let options = new RequestOptions({ headers: headers });

        return this.http.post(this.API_URL + id, null,options);
    }

    get() {
        let headers = new Headers();
        headers.append('Authorization', "Bearer " + this.authService.token);

        let options = new RequestOptions({ headers: headers });
        return this.http.get(this.API_URL,  options).map(res => res.json());
    }

    update(entry: Entry){

        let headers = new Headers();
        headers.append('Authorization', "Bearer " + this.authService.token);

        let options = new RequestOptions({ headers: headers });
        return this.http.put(this.API_URL, entry, options);
    }

这是组件的代码:

import { Component, OnInit } from '@angular/core';
import { EntryService } from "../../services/entry.service";
import { MasterCodeService } from "../../services/masterCode.service";
import { SubCodeService } from "../../services/subcode.service";
import { Entry } from "../../models/entry";
import { MasterCode } from "../../models/masterCodes";



@Component({
    selector: 'entry-list',
    templateUrl: './entry-list.component.html'
})
export class EntryListComponent implements OnInit {



    private readonly PAGE_SIZE = 100;


    query: any = {
        pageSize: this.PAGE_SIZE
    };
    masterCodes: any = [];
    subCodes: any = [];
    masterCode: MasterCode = new MasterCode();
    entries: Entry[];
    entry: Entry ={
        id: [],
        masterCodeId: 0,
        subCodeId: 0,
        accepted: 0,
        rejected:0
};


columns = [
        { title: "#" },
        { title: "PO" },
        { title: "SKU" },
        { title: "Status" }
    ];
    constructor(private entryService: EntryService,
        private masterCodeService: MasterCodeService,
        private subCodeService: SubCodeService) {

    }

    load() {
        this.masterCodeService.getMasterCodes(this.query).subscribe(res => {
            this.masterCodes = res;
        });
        this.entryService.get().subscribe(res => {
            this.entries = res;

        });

    }

    ngOnInit() {
        this.load();


    }

    onChange(event) {
        var selectedMasterCode = this.masterCodes.items.find(x => x.id == event.target.value);
        this.entry.masterCodeId = selectedMasterCode.id;
        this.subCodeService
            .getSubCodes()
            .subscribe(res => this.subCodes = res.filter(x=>x.masterCode.id == selectedMasterCode.id));
    }

    submit(event) {

        if (event.target["noError"]) {

                this.entry.accepted = 0;
                this.entry.rejected = 0;
        }
        if (event.target["accepted"] && event.target["accepted"].checked === true ) {
            this.entry.accepted = 1;
            this.entry.rejected = 0;


        }
        if (event.target["rejected"] && event.target["rejected"].checked === true ) {
            this.entry.accepted = 0;
            this.entry.rejected = 1;
        }


        this.entryService.update(this.entry).subscribe(x => {
            location.reload();
            this.load();
        });
    }

    selectSubCode(event) {
        this.entry.subCodeId = event.target.value;
    }


    onEntryToggle(entryId, $event) {
        if ($event.target.checked)
            this.entry.id.push(entryId);
        else {
            var index = this.entry.id.indexOf(entryId);
            this.entry.id.splice(index, 1);
        }

    }



}

调用提交后,我收到下一个错误:

处理请求时发生未处理的异常。 JsonReaderException:解析时遇到意外字符 价值: {。路径“errorMessage”,第 1 行,位置 17。 Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType)

堆栈查询 Cookie 标头 JsonReaderException:意外字符 解析值时遇到:{。路径“errorMessage”,第 1 行, 位置 17. Newtonsoft.Json.JsonTextReader.ReadStringValue(ReadType readType) Newtonsoft.Json.JsonTextReader.ReadAsString() Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ReadForType(JsonReader reader, JsonContract 合约, bool hasConverter) Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(对象 newObject,JsonReader 阅读器,JsonObjectContract 合约, JsonProperty 成员,字符串 id) Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, 对象现有值) Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, 对象现有值) Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader 阅读器,类型 objectType,bool checkAdditionalContent) Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader 阅读器, 类型 objectType) Newtonsoft.Json.JsonConvert.DeserializeObject(string 值、Type 类型、JsonSerializerSettings 设置) Newtonsoft.Json.JsonConvert.DeserializeObject(字符串值, JsonSerializerSettings 设置) Microsoft.AspNetCore.NodeServices.HostingModels.HttpNodeInstance+d__7.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) System.Runtime.CompilerServices.TaskAwaiter.GetResult() Microsoft.AspNetCore.NodeServices.HostingModels.OutOfProcessNodeInstance+d__13.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) System.Runtime.CompilerServices.TaskAwaiter.GetResult() Microsoft.AspNetCore.NodeServices.NodeServicesImpl+d__10.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) System.Runtime.CompilerServices.TaskAwaiter.GetResult() Microsoft.AspNetCore.NodeServices.NodeServicesImpl+d__10.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) System.Runtime.CompilerServices.TaskAwaiter.GetResult() Microsoft.AspNetCore.SpaServices.Prerendering.PrerenderTagHelper+d__29.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner+d__0.MoveNext() System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务 任务) AspNetCore._Views_Home_Index_cshtml+d__12.MoveNext() 在 索引.cshtml

请你给我建议如何解决这个问题? 附言如果我不提交表单只是按 F5 重新加载页面,我也会遇到同样的错误。

更新 这是第一次调用的 JSON:

重新加载后:

标题第一次调用:

重新加载后的标题:

我对某些 URL 路径重新加载的理解是有效的,而其中一些无效。回顾一下,有些路由可以手动输入到浏览器中调用,而其中一些只能从链接调用,为什么?如果所有链接、所有组件、所有服务都是以相同的方式创建的,我怎么能确定错误在哪里? 亲切的问候, 丹尼尔

【问题讨论】:

  • 你能告诉我们它试图解析的 JSON 吗?
  • 我有更新问题。补充一点,当我调用 GET 时,我在后端设置了断点。在第一次调用时它正在工作,如果我尝试重新加载页面,GET 根本不会调用。
  • 抱歉,您可以查看网络面板,而不是您添加的内容,然后添加发送到后端的实际 JSON 吗?它需要在失败的请求之一上
  • 现在可以了吗?
  • 我可以看到不同之处在于标头,重新加载时它没有调用正确的 URI。

标签: c# .net angular typescript asp.net-core


【解决方案1】:

我已经用代码修复了

load() {
    this.entryService.get().subscribe(res => {

        this.entries = res;
},err=>console.log(err));
this.masterCodeService.getMasterCodes(this.query).subscribe(res => {
    this.masterCodes = res;
});



}

这对我来说是解决方案,老实说这对我有什么帮助以及为什么我应该添加 err=>console.log(err) 不知道。如果有人能澄清我这一点,将不胜感激。

**我错了,解决方案在 app.shared.ts 在路由配置中我添加了 canActive

{ 路径:'entries',组件:EntryListComponent,canActivate:[AuthGuard]},

由于 API 已获得授权,因此这是强制性的。**

【讨论】:

    猜你喜欢
    • 2017-11-14
    • 2018-06-21
    • 2017-12-06
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多