I want to have 3 fields with editable text, when I use my method getTexts() it works and the text is displayed in the fields. However when I try to update those texts and update the new values, the http request is never made. I don't get any console errors.
This is my service:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { URLSearchParams, QueryEncoder } from '@angular/http';
import { Texts } from '../classes/texts';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class TextsService {
private getTextsUrl = 'myurl';
private updateTextsUrl = 'myurl';
constructor (private http: Http){}
getTexts(): Observable<Texts>{
return this.http.get(this.getTextsUrl)
.map(this.handleData)
.catch(this.handleError);
}
private handleData(res: Response){
let body = res.json();
return body;
}
private handleError (error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
return Observable.throw(errMsg);
}
updateTextos(texts: Texts): Observable<any>{
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
let body = new URLSearchParams();
Object.keys(texts).forEach(key => {
body.set(key, texts[key]);
})
This is where the code stops and the http post is never executed
return this.http.post(this.updateTextsUrl, body.toString(), options)
.map(this.handleDataAdd)
.catch(this.handleError);
}
}
This is my component:
import { Component, OnInit } from '@angular/core';
import { TextosService } from '../../../services/textos.service';
import { Textos } from '../../../classes/textos';
@Component({
selector: 'app-editar-textos',
templateUrl: './editar-textos.component.html',
styleUrls: ['./editar-textos.component.css'],
providers: [TextsService]
})
export class EditTextsComponent implements OnInit {
public texts: Textos;
errorMessage: string;
constructor(private textsService: TextsService) { }
ngOnInit() {
this.getTexts();
}
onSubmit(){
this.updateTexts();
}
updateTextos(){
this.textsService.updateTexts(this.texts);
}
getTexts(){
this.textsService.getTexts()
.subscribe(
result => {
this.texts = new Texts(1, result[0].property1, result[0].property2, result[0].property3);
},
error => this.errorMessage = error
)
}
}