sensei
sensei

Reputation: 7552

Angular2 not making post request

I can't make post working. It doesn't trigger my endpoint, and there is no request in developer tools made towards web api.

Http service:

@Injectable() export class DataService {

private _apiurl: string;
private _headers: Headers;
private _options: RequestOptions;
private _apiEndpoint : string;

constructor(public http: Http, public _securityService : OidcSecurityService) {
    this.setHeaders();
}

public setEndpoint(endpointUrl : string){
    this._apiurl = AppSettings.API_URL + endpointUrl;
}

private setHeaders() {

    console.log('setHeaders started');

    this._headers = new Headers();
    this._headers.append('Content-Type', 'application/json');
    this._headers.append('Accept', 'application/json');

    let token = this._securityService.GetToken();

    if (token !== '') {
        let tokenValue = 'Bearer ' + token;
        console.log('tokenValue:' + tokenValue);
        this._headers.append('Authorization', tokenValue);
    }

    this._options = new RequestOptions({ headers: this._headers, body: '' });
}

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

public GetSingle = (id: number): Observable<any> => {
    return this.http.get(this._apiurl + '/' + id, this._options).map(res => <any>res.json());
}

public Create = (item: any): Observable<any> => {
    console.log(JSON.stringify(item) + " keke")

    return this.http.post(this._apiurl, JSON.stringify(item), this._options).map(res => <any>res.json());
}

public Update = (id: number, item: any): Observable<any> => {
    return this.http.put(this._apiurl + '/' + id, JSON.stringify(item), this._options).map(res => <any>res.json());
}

public Delete = (id: number): Observable<any> => {
    return this.http.delete(this._apiurl + id);
}

}

Component:

  create() {
    var result,
        userValue = this.form.value;

        console.log(userValue.Id + ", userValueId");
      this.dataService.setEndpoint('/api/program/create');
      this.dataService.Create(userValue);

  }

Upvotes: 0

Views: 31

Answers (1)

Leon Radley
Leon Radley

Reputation: 7672

Because observables are like a recipe, they don't get executed until you "bake" them by calling .subscribe()

in your case you need to call

this.dataService.Create(userValue).subscribe();

Upvotes: 4

Related Questions