1

Hey (1st time posting here so I may break some rules, tell me if I do),

I'm trying to create a Rest API and I have some problems with. In fact, the post function is not triggered on the C# API and I don't know why while the GET function used with a getAll() function is running good.

Angular Service :

public GetAll = (): Observable<Expertise[]> => {
        return this.http.get(this.actionUrl, '').map((response: Response) => <Expertise[]>response.json());
}

public Add = (thingToAdd: Expertise): Observable<Expertise> => {
    thingToAdd.Id = 1;
    let toAdd = JSON.stringify(thingToAdd);
    console.log(toAdd);
    console.log(this.actionUrl);
    return this.http.post(this.actionUrl, toAdd, { headers: this.headers 
}).map((response: Response) => response.json());
}

C# API :

// GET api/values
    [HttpGet]
    public async Task<IEnumerable<Expertise>> Get()
    {
        try
        {
            System.Console.WriteLine("Test get all");
            //var result = await cvService.Get("toto@azeo.com");
            return new List<Expertise>();
        }
        catch (System.Exception ex)
        {
            logger.LogError(ex.Message, ex);
            throw;
        }
    }
// POST api/values
    [HttpPost]
    public Expertise Post([FromBody]Expertise expertise)
    {
        try
        {
            System.Console.WriteLine("Test post");
            context.Expertises.Add(expertise);
            context.SaveChanges();

        logger.LogInformation("New expertise added !");
        return expertise;
        }
        catch (System.Exception ex)
        {
            logger.LogError(ex.Message, ex);
            throw;
        }
    }

Expertise (EF model) :

public class Expertise
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public ICollection<ExpCV> CVs { get; set; }
}

If anyone has an idea to "link" the service and my API tell me, I'm stuck on it for a since a long time.

Thank you in advance

Nicolas S.
  • 173
  • 2
  • 12
  • Is the http request executed? What is the return? – misha130 May 05 '17 at 13:24
  • The post one looks like to not be executed meanwhile the get one is executed – Nicolas S. May 05 '17 at 13:26
  • How do you call your 'getAll' and 'add' ? You have to subscribe to each of them so that the call is made. – Ahmed Musallam May 05 '17 at 13:41
  • ngOnInit() { this.expertise = new Expertise(); this.listeExpertise = this.service.GetAll(); } public addExpertise() { this.service.Add(this.expertise); } @AhmedMusallam – Nicolas S. May 05 '17 at 13:53
  • this code come form the component in typescript – Nicolas S. May 05 '17 at 13:55
  • you need to subscribe to them, try `this.service.Add(this.expertise).subscribe(console.log, console.log)` this should send the post request and log the response json – Ahmed Musallam May 05 '17 at 13:56
  • Gonna try but why then my getAll() is running without the subscription ? – Nicolas S. May 05 '17 at 13:57
  • Running ! but I got this error now `fail: Azeo.CVTheque.Controllers.ExpertiseController[0] Object reference not set to an instance of an object.` – Nicolas S. May 05 '17 at 14:00
  • @NicolasS. so the `post` request happens? and you get this error in your backend? this seems like a C# error.. dont know much about C# but see this: http://stackoverflow.com/questions/20140047/how-to-solve-object-reference-not-set-to-an-instance-of-an-object – Ahmed Musallam May 05 '17 at 15:13
  • I found the solution on this ! Will put an answer asap :D – Nicolas S. May 05 '17 at 15:18
  • Thanks a lot ! :D – Nicolas S. May 05 '17 at 15:19
  • @NicolasS. I added an answer explaining when the request are sent when using the http service for angular as this is your question.. any C# errors you are seeing are not related to the question. thanks :) – Ahmed Musallam May 05 '17 at 15:30

1 Answers1

0

since your service returns an observable the actual GET and POST requests will NOT happen until you subscribe to that observable.

take a look at this plunker I set up:

plunker: https://plnkr.co/edit/r6aBaB3BjJzdIS4myAd8?p=preview

code:

@Component({
    selector: 'app',
    template: `
        <button (click)="searchNoSub()">searchNoSub</button>
        <button (click)="search()">search</button>
    `
})

export class App {

    constructor(private searchService:SearchService) {
    }

    search(){
        this.searchService.search().subscribe(console.log,console.log)
    }
    searchNoSub(){ this.searchService.search(); }
}

searhService:

@Injectable()
export class SearchService {

  constructor(private http: Http) {}

  search(term: string) {
    // get artists named john from spotify API
    return this.http.get('https://api.spotify.com/v1/search?q=john&type=artist')
      .map((response) => response.json());
  }
}

now open your devtools and network tab in chrome to look at new requests:

when clicking the searchNoSub you'll notice no requests are registered in network tab. when clicking search button, you'll see a request because we subscribed.

In short, you need to subscribe to the request observable.

Ahmed Musallam
  • 9,523
  • 4
  • 27
  • 47