Угловая 5 "карта не определена" - PullRequest
0 голосов
/ 11 мая 2018

У меня есть приложение .Net 4.6.2 VS 2017 Mvc, с Angular 5, "rxjs": "^ 5.5.10"

Я пытаюсь получить данные для сетки Kendo UI через контроллер.Контроллер возвращает данные, которые я вижу, но в классе обслуживания по коду .map (response => response.json ()) он говорит о недопустимом выражении возврата (см. Прикрепленное изображение) image

err img2

Вот vto.service.ts

   import { Injectable } from '@angular/core';
    import { VTO } from './vto';
    import { Http, HttpModule, Headers,  Response } from '@angular/http';
    import { HttpClientModule, HttpClient, HttpHeaders} from '@angular/common/http';
    import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common';
    import { Observable } from 'rxjs/Observable';
    import 'rxjs/Rx';
    import { BehaviorSubject } from 'rxjs/BehaviorSubject';
    const httpOptions = {
        headers: new HttpHeaders({ 'Content-Type': 'application/json' })
    };
    import {
        toDataSourceRequestString,
        translateDataSourceResultGroups,
        translateAggregateResults,
        DataResult,
        DataSourceRequestState
    } from '@progress/kendo-data-query';
    import 'rxjs/add/operator/map';

    import { GridDataResult, DataStateChangeEvent } from '@progress/kendo-angular-grid';

    @Injectable()
    export class Vtos {


       //  private vtoUrl = location.href.replace(location.hash, '') + '/home/GetVtos';

        private vtoUrl = 'http://localhost:63213/Home/GetVtos';

        constructor(private http: Http) { }

            public getVtos(state: DataSourceRequestState): Observable<DataResult> {

            const queryStr = `${toDataSourceRequestString(state)}`; //serialize the state
            const hasGroups = state.group && state.group.length;
            return this.http
              .get(`${this.vtoUrl}?${queryStr}`) //send the state to the server
              .map(response => response.json())
              .map(({ data, total/*, aggregateResults*/ }) => // process the response
                (<GridDataResult>{
                  //if there are groups convert them to compatible format
                  data: hasGroups ? translateDataSourceResultGroups(data) : data,
                  total: total,
                  // convert the aggregates if such exists
                  //aggregateResult: translateAggregateResults(aggregateResults)
                }))
        }
    }

Вызов HomeController для GetVots

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VTO.DTO;
using VTO.DAL;
using Kendo.Mvc.UI;
using Kendo.Mvc.Extensions;
namespace VTO.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public JsonResult GetVtos([DataSourceRequest]DataSourceRequest request)
        {
            return new JsonResult
            {
                ContentType = "application/json",
                Data = Vto.GetVtos().ToDataSourceResult(request),
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = int.MaxValue
            };
        }
}

Ответы [ 2 ]

0 голосов
/ 14 мая 2018

Поделиться тем, что у меня сработало. Поскольку Луиллиф упомянул, что Http сейчас устарел, HttpClient должен использоваться. Возвращенный ответ уже находится в Json, поэтому больше не нужно использовать метод .Json.

constructor(private http: HttpClient) { }
public getVtos(state: DataSourceRequestState): Observable<DataResult> {
    const queryStr = `${toDataSourceRequestString(state)}`; //serialize the state
    const hasGroups = state.group && state.group.length;
    return this.http
        .get(`${this.vtoUrl}?${queryStr}`) //send the state to the server
        .pipe(
        map(<DataResult>({ Data, Total/*, aggregateResults*/ }) => {// process the response
            console.log(Data);
            return (<GridDataResult>{

                data: hasGroups ? translateDataSourceResultGroups(Data) : Data.map(item => {
                    item.ReportDate = new Date(item.ReportDate); // convert to actual JavaScript date object
                    return item;
                }),
                total: Total

            })
        })
        )
}
0 голосов
/ 12 мая 2018

Пара замечаний здесь, , этот модуль устарел . Подробнее см. Здесь . Удалите его из приложения.

import { Http, HttpModule, Headers,  Response } from '@angular/http';

Вы должны использовать HttpClientModule,

import { HttpClient, HttpHeaders} from '@angular/common/http';

Имейте в виду, что вам нужно импортировать HttpClientModule на свой app.module.ts (или любой другой модуль, для которого у вас есть зависимость)

import { HttpClientModule } from '@angular/common/http';

С тех пор как HttpClientModule вступил в игру.Вам больше не нужно для response.json().Теперь HttpClient.get() возвращает Observable с типизированным HttpResponse, а не только данные JSON. См. Документы .( vto.service.ts )

Удалить,

.map(response => response.json())

Тогда у вас есть,

constructor(private http: HttpClient) { }

public getVtos(state: DataSourceRequestState): Observable<DataResult> {
  ...
  return this.http
          .get(`${this.vtoUrl}?${queryStr}`)
          .map(({ data, total/*, aggregateResults*/ }) =>
            (<GridDataResult>{
              data: hasGroups ? translateDataSourceResultGroups(data) : data,
              total: total,
              translateAggregateResults(aggregateResults)
            }))
}
...