“ this.http.get(...)。catch不是函数” angular8

时间:2019-09-22 14:24:21

标签: javascript angular

我想使用角度8的catch,但这给了我错误。

data.service.ts

import { BadInput } from './../common/bad-input';
import { AppError } from './../common/app-error';
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs';
import { NotFoundError } from '../common/not-found-error';
import { catchError } from 'rxjs/operators';



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


  constructor(private url : string ,private http : Http) { }

  getAll(){
    return this.http.get(this.url).
    catch(this.handleError);
  }

  create(resource){
    return this.http.post(this.url,resource)
    .catch(this.handleError);
    ;
  }

  update(resource){
    return this.http.put(this.url,resource)
    .catch(this.handleError)
  }

  delete(resource){
    return this.http.delete(this.url+'/'+resource.id)
    .catch(this.handleError)

  }

    private handleError(error : Response){
      if(error.status===404){
        return Observable.throw(new NotFoundError);
      }

      if(error.status===400){
        return Observable.throw(new BadInput)
      }

      return Observable.throw(new AppError)

    }
}

post.service.ts

import { Http } from '@angular/http';
import { DataService } from './data.service';
import { Injectable } from '@angular/core';


@Injectable({
  providedIn: 'root'
})
export class PostService extends DataService {

  constructor(http : Http) {
    super('https://jsonplaceholder.typicode.com/posts',http);
   }
}

post.component.ts

import { BadInput } from './../common/bad-input';
import { AppError } from './../common/app-error';
import { PostService } from './../services/post.service';
import { Component, OnInit } from '@angular/core';
import { NotFoundError } from '../common/not-found-error';
import { throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Component({
  selector: 'posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
  posts:any[]=[];
  status=true;
  post={
    id:0,
    title:'',
    body:'',
    userId:''
  };


  constructor( private postService : PostService ) {

  }

  ngOnInit() {
    this.getPost(

    );
  }

  getPost(){
    this.postService.getAll()
     .subscribe(
       response=>{
       this.posts=response.json();
    },error=>{
      alert('error innattendue')
      console.log(error)
    }
    );
  }

  createPost(){
    this.postService.create(this.post)
    .subscribe(response=>{
         this.post.id=response.json().id;
         this.posts.unshift(this.post);
         this.post={
          id:0,
          title:'',
          body:'',
          userId:''
        }        
    },(error:AppError)=>{
      if(error instanceof BadInput){
        alert('c post deja supprimer')
      }else{
        alert('error inattendue')
      }
    }
    )
  }

  EditPost(post){
    this.post = post ;
    this.status=false;
  }

  updatePost(){
    this.postService.update(this.post)
     .subscribe(response=>{
      this.post={
        id:0,
        title:'',
        body:'',
        userId:''
      }
      this.status=true;  
     })
  }

  delete(post){
    this.postService.delete(post)
    .subscribe(response => {
      console.log(response)
      let index = this.posts.indexOf(post);
      this.posts.splice(index,1);
    },(error:AppError)=>{
      if(error instanceof NotFoundError){
        alert('c post deja supprimer')
      }else{
        alert('error inattendue')
      }
    })
  }
}

2 个答案:

答案 0 :(得分:0)

如果您确实想捕获错误,可以使用angular http来完成。只是使语法错误,没有别的。

this.http.get('your_url').then( data => {
   //here you do something post success
}).catch( error => {
  //pass the error status to your handle error and do whatever you want
  this.handleError(error.status);
});

这样,如果它来自服务器,则将获得您想要实现的目标。谢谢:)

答案 1 :(得分:0)

使用:


import { HttpClient } from '@angular/common/http';

constructor(private http: HttpClient) {}

request(): void {
this.http.get("/uri", {
        params: {},
            observe: 'response'
        }).toPromise().then((res: any) => {
            console.log(res.body);
        }).catch((err :any) => {

        });
}

我认为Http不是必须使用HttpClient的有效软件包