0

This used to be a 415 error question.

Now it is a a receiving null values on the server side question.

I am having difficulty trying to get my values in the object myMessage over to the server side.

I have so far tried to add JSON.stringify to newMessage which is being console.logged in the service file.

I tried many ways to alter or make the object the way it would be recognized such as JSON.stringify() and creating a url ending with the correct parameters.

Sorry if it seems like I am dumping code below, but I have been working on this for a second day and don't understand why I can't do a simple post request with three parameters. One string, one int, and one datetime.

If anyone can see where I have gone wrong I would so appreciate it. I will be desperately waiting. Below I am trying to hit api/SlgCorpNotes/Edit in backend from updateMessage(message: any) in the service in service.ts

slg-corp-notes.service.ts

import { Component, Injectable, Inject } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';
import { Observable, Subject, BehaviorSubject } from 'rxjs';
import { SLGReportParams, CorpNotes } from './models/slg.model';
import { SlgOverviewComponent } from './slg-overview/slg-overview.component';
import { SlgNote } from './models/slg-notes';

@Injectable({
  providedIn: 'root'
})
export class SlgCorpNotesService {

  constructor(private http: HttpClient, @Inject('BASE_URL') private baseUrl: string) { }

  getWeekTempValue(endDate, department) {
    var Params = '?endDate=' + endDate + '&department=' + department;
    return this.http.get<any>(this.baseUrl + 'api/SlgCorpNotes/getWeekTempValue' + Params);
  }

  updateMessage(message: any) {
    console.log("at service")
    console.log(message)
    var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
    var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
    console.log(newMessage)
    console.log(JSON.stringify(newMessage))
    console.log(Params)
const headers = new HttpHeaders()
  .set('Content-Type', 'application/json;charset=UTF-8')

let options = { headers: headers };

return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options).subscribe(res => {
  console.log(res);
}, error => {
  console.log(error);
});;
  }

}

model.ts

export class CorpNotes {
  constructor(
    public department: number,
    public note: string,
    public weekEnding: Date
  ) { }
}

SLGCorpNotesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using mocHub2.Models;
using mocHub2.Models.Enterprise;
using Microsoft.EntityFrameworkCore;
using System.Data.SqlClient;

namespace mocHub2.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SlgCorpNotesController : Controller
    {
        SLGContext _SLGContext;
        BRDataContext _BRDataContext;

        //injects new context
        public SlgCorpNotesController(SLGContext context, BRDataContext context2)
        {
            _SLGContext = context;
            _BRDataContext = context2;
        }

        // GET: api/SlgCorpNotes
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET: api/SlgCorpNotes/5
        [HttpGet("{id}", Name = "Get")]
        public string Get(int id)
        {
            return "value";
        }

        // POST: api/SlgCorpNotes
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // Get Corporate Notes
        [HttpGet("[action]")]
        public JsonResult getWeekTempValue(DateTime endDate, int department)
        {

            //  Find the WeekID from the weekending from SLGHeaderTemplate table
            var WeekID = (from x in _SLGContext.SlgheaderTemplate
                          where x.WeekEnding == endDate
                          select x.Id).ToList();
            //  Find Department name by ID
            var DepartmentString = (from x in _BRDataContext.Departments
                                    where x.Department == department
                                    select x.Description).ToList();
            //  Get the Note.
            var DeptNote = from x in _SLGContext.SLGCorpNotes
                           where x.Department == DepartmentString[0]
                           && x.WeekID == WeekID[0]
                           select x.Notes;

            //  Create return object
            var notes = new Notes();

            //  If Note exists then return Json containing note and department for display, else return empty string.
            if (DeptNote.Any() && WeekID.Count() > 0 && DepartmentString.Count() > 0)
            {
                var ReturnDeptNote = DeptNote.First();
                notes = new Notes() { WeekID = WeekID[0], Department = DepartmentString[0], Note = ReturnDeptNote };
            }
            else
            {
                var ReturnDeptNote = "";
                notes = new Notes() { WeekID = WeekID[0], Department = DepartmentString[0], Note = ReturnDeptNote };
            }

            return Json(notes);
        }

        [HttpPost]
        [Route("Edit")]
        public void Edit([FromForm] CorpNotes item)
        {

            _SLGContext.Entry(item).State = EntityState.Modified;
            _SLGContext.SaveChanges();
        }
    }

    public class CorpNotes
    {
        public int department { get; set; }

        public string note { get; set; }

        public DateTime weekEnding { get; set; }
    }

    public class Notes
    {
        public int ID { get; set; }

        public int WeekID { get; set; }

        public string Department { get; set; }

        public string Note { get; set; }

    }
}

Results of console.logs in the service file.

at service
slg-corp-notes.service.ts:22 {departments: 2, weeks: SLGTime, noteBody: "asdf"}
slg-corp-notes.service.ts:25 CorpNotes {department: 2, note: "asdf", weekEnding: "2019-11-02T00:00:00"}
slg-corp-notes.service.ts:26 {"department":2,"note":"asdf","weekEnding":"2019-11-02T00:00:00"}
slg-corp-notes.service.ts:27 ?Department=2&Note=asdf&WeekEnding=2019-11-02T00:00:00
slg-corp-notes.service.ts:28 Observable {_isScalar: false, source: Observable, operator: MapOperator}

app.module.ts This is in my app.module.ts where I specify routes

  { path: 'slg-corp-notes', component: SlgCorpNotesComponent },
  { path: 'slg-corp-notes/edit/', component: SlgCorpNotesComponent }

slg-corp-notes.component.ts

  save() {
    console.log("at save")
    if (!this.optionsForm.valid) {
      return;
    }
    //this.Notes.note = this.optionsForm.get['noteBody'].value;
    console.log(this.Notes);
    this._slgCorpNotesService.updateMessage(this.optionsForm.value)
      .subscribe((data) => {
        this._router.navigate(['/slg-corp-notes']);   //This will navigate back to the mochhub2 index where the message will be displayed
      }, error => this.errorMessage = error)
  }

Please let me know if additional info is needed.

6
  • Try removing routing from Route attribute as it is already defined in controller lebel. e.g '[Route("api/SlgCorpNotes/Edit")]' to '[Route("Edit")] Commented Oct 30, 2019 at 17:35
  • Okay! Now were getting somewhere. I now have a 415 error; zone.js:3243 POST localhost:44320/api/SlgCorpNotes/Edit 415 (Unsupported Media Type) Does this mean I have to stringify something? Commented Oct 30, 2019 at 17:42
  • look into my answer Commented Oct 30, 2019 at 18:11
  • Elon, I did so but I am receiving the ouput above. After switching to [Route("Edit")] it is now receiving a 415 error. The data is not being accepted by the controller method Edit Commented Oct 30, 2019 at 18:19
  • Hey! So, I am getting through into the method without a 415 error by changing FormBody to FormForm, but I am receiving null values for all my values. Would you know why this is the case? Commented Oct 30, 2019 at 19:02

2 Answers 2

2

1) You need to set the Content-Type header to application/json.

2) stringify the message.

const headers = new HttpHeaders()
     .set('Content-Type', 'application/json;charset=UTF-8')     

let options = { headers : headers };

this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', JSON.stringify(newMessage), options);
Sign up to request clarification or add additional context in comments.

7 Comments

Hey EyIM I think were getting close. I tried what you posted but I am still getting the 415 error. This is my newMessage object. Do you see anything that might need to be done to it other than Json.stringify? console.log(newMessage) result below: CorpNotes {department: 2, note: "asdf", weekEnding: "2019-11-02T00:00:00"} department: 2 note: "asdf" weekEnding: "2019-11-02T00:00:00" proto: Object
Please update the code in the question with current code and the error.
You are doing the post 2 times in the code. one of them with old parameters in the logging function. also, add charset=utf-8 as.
I have updated the question and have put the output now. It seems to not like the json object that is comming through. It now is recognizing the endpoint and finding the Edit method in the controller but exiting with 415 error
Ok, I added charset=utf-8, and removed the post from the logging function
|
1

At your angular side update your method like this

    updateMessage(message: any) {
    console.log("at service")
    console.log(message)
    var newMessage = new CorpNotes(message['departments'], message['noteBody'], message['weeks'].weekEnding)
    var Params = '?Department=' + message['departments'] + '&Note=' + message['noteBody'] + '&WeekEnding=' + message['weeks'].weekEnding
    console.log(newMessage)
    console.log(JSON.stringify(newMessage))
    console.log(Params)


   var item = {
    "Departments": message["Departments"],
    "Note": message["noteBody"],
    "WeekEnding": message["weeks"]
   }

    return this.http.post(this.baseUrl + 'api/SlgCorpNotes/Edit', item).subscribe(res 
      => {
       console.log(res);
    }, error => {
         console.log(error);
    });
  }

5 Comments

Hey Elon, I tried this but it didn't work and still getting a 415 error. I dont think i need a suscribe on this, or else it gives an error on the suscribe on my conponent.ts file where there is already a suscribe before it makes a request to the service
@JSkyS Have you tried enabling CORS Just add this attribute [EnableCors] above your method in .net side just before [HttpPost]
Hey Elon, I didnt need cors now that im hitting the backend method, but now the data is coming through null so I think there is still something wrong with the object I am sending back.
Thank you for your help. I used your idea on creating the object then passing it. One thing extra I had to do was input the Content Type in the header. const headers = new HttpHeaders() .set('Content-Type', 'application/json;charset=UTF-8') let options = { headers: headers };
Thanks! Maybe you could up vote my question for up voting and selecting your answer as the answer. I think its awesome what your doing with Space X and I really like the new model 3. Maybe I might consider buying one if you came out with a model 2 that was a little smaller. Kind of like a hatchback model. Anyways, I hope to be able to have a Tesla in my garage if they are a little more affordable. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.