首页 > 解决方案 > Angular4 TypeScript JsonReaderException

问题描述

我有向用户显示的包含 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 contract, bool hasConverter) Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, string id) Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, object existingValue) Newtonsoft.Json。

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

更新 这里是第一次调用的 JSON: 在此处输入图像描述 从网络面板

重新加载后: 在此处输入图像描述

标题第一次调用: 在此处输入图像描述

重新加载后的标题: 在此处输入图像描述

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

标签: c#.netangulartypescriptasp.net-core

解决方案


我用代码修复了

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

{ 路径:“条目”,组件:EntryListComponent,canActivate:[AuthGuard]},

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


推荐阅读