Angular http帖子不起作用

时间:2017-10-18 17:16:55

标签: angular

我希望有3个带可编辑文本的字段,当我使用我的方法getTexts()时,它可以工作,文本显示在字段中。但是,当我尝试更新这些文本并更新新值时,永远不会发出http请求。我没有收到任何控制台错误。

这是我的服务:

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]);
        })

这是代码停止的地方,http帖子永远不会执行

    return this.http.post(this.updateTextsUrl, body.toString(), options)
        .map(this.handleDataAdd)
        .catch(this.handleError);
    }
}

这是我的组成部分:

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
    )
  }

}

0 个答案:

没有答案