Угловая ошибка синтаксического анализа JSON из Promise Return - PullRequest
0 голосов
/ 02 июля 2019

Я пытаюсь получить имя из обещания, которое я написал, и я могу нажать API с почтальоном, и на своей вкладке сети я вижу запрос, но в консоли я получаю ошибку разбора.

Мой компонент выглядит как

  generateAppointments(companyID): any {

    this.appointments = null;
    this.appointmentService.getAppointmentsByCompanyID(companyID).then(r => {
      console.log(r);
      this.appointments = r;
      this.appointments.forEach((item, index) => {
        let customerName = this.getCustomerNameByID(item.customerID);
        console.log(customerName);
        let newAppointment = {
          id: item.appointmentID,
          description: item.appointmentNotes,
          subject: customerName,
          //calendar: this.getCustomerNameByID(item.customerID),
          observCat: item.customerID,
          observSub: item.observationCategoryID,
          start: new Date(item.appointmentDate),
          end: new Date(item.appointmentEndDate),
        }
        this.scheduler.addAppointment(newAppointment);
      });
    });
    //console.log(this.source);

  };

который звонит

  getCustomerNameByID(customerID) {
    this.appointmentService.getCustomerNameByCustomerID(customerID)
      .then(data => { this.customerName = data; return data; }).catch(err => 
      console.log(err));

  }

Сервисное обещание выглядит так:

  getCustomerNameByCustomerID(customerID): Promise<string> {
    return this.httpClient.get<string>(this.baseUrl + 
     'api/Appointments/GetCustomerNameByCustomerID?CustomerID=' + customerID)
      .toPromise()
      .then((res) => { console.log(res); return res; });
  }
}

Моя консольная ошибка Chrome:

"SyntaxError: Unexpected token S in JSON at position 0
    at JSON.parse (<anonymous>)
    at XMLHttpRequest.onLoad (http://localhost:5000/vendor.js:7509:51)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:5000/polyfills.js:2768:31)
    at Object.onInvokeTask (http://localhost:5000/vendor.js:48600:33)
    at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:5000/polyfills.js:2767:60)
    at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:5000/polyfills.js:2540:47)
    at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:5000/polyfills.js:2843:34)
    at invokeTask (http://localhost:5000/polyfills.js:4089:14)
    at XMLHttpRequest.globalZoneAwareCallback (http://localhost:5000/polyfills.js:4126:21)"

Текст, который он возвращает и пытается проанализировать, - "Smith,Benjamin 0014662" Я не знаю, почему он пытается проанализировать JSON, я просто хочу вернуть это значение.

Я пытаюсь установить это значение в переменной newAppointment, но он запрашивает subject:, чтобы быть строкой, но жалуется, что она недействительна, что я считаю не связанным, но не уверен.

Я новичок в angular, поэтому я не очень знаком со всем этим. Конечная точка возвращает то, что мне нужно, но я не уверен, почему он считает, что результат должен быть проанализирован из JSON.

РЕДАКТИРОВАТЬ У меня есть console.log (customerName), который возвращает неопределенное значение. Как я уже сказал, API возвращает: "Smith,Benjamin 0014662", но мой TS не получает это значение и вместо этого жалуется на ошибку разбора.

Ответы [ 2 ]

0 голосов
/ 02 июля 2019

Поскольку этот API возвращает текстовое тело, вы можете сделать следующее.

getCustomerNameByCustomerID(customerID): Promise<string> {
  return this.httpClient.get(this.baseUrl + 
    'api/Appointments/GetCustomerNameByCustomerID?CustomerID=' + customerID, { responseType: 'text' })
    .toPromise()
    .then((res) => { console.log(res); return res; });
}

FYI: по умолчанию HttpClient пытается проанализировать ответ в объект JSON, если не указано иное. Добавление responseType как text скажет HttpClient ожидать ответ в виде строки, а не анализировать его.

0 голосов
/ 02 июля 2019

сначала проверьте ваш возвращаемый json, это происходит при синтаксической ошибке json и, если это не так, объявляйте дополнения как массив

let appointments =[];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...