ค้นหาเว็บไซต์

typescript - วิธีการนำเข้า property map ของ rxjs ในโปรเจกต์ angular, ข้อผิดพลาด: Property 'map' ไม่มีอยู่ในประเภท 'Observable<Object>'?


ฉันกำลังโพสต์ข้อมูลบนเซิร์ฟเวอร์ใน Angular ด้วยคำขอ http post และด้วย rxjs แต่แม้หลังจากที่นำเข้าคุณสมบัติ map ของ rxjs แล้ว ก็ยังมีข้อผิดพลาดเกิดขึ้น

import { Injectable } from '@angular/core';
import {HttpClient,HttpHeaders,HttpErrorResponse} from '@angular/common/http';
import {throwError } from 'rxjs';

import 'rxjs/add/operator/map';

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


  constructor(private http:HttpClient) { }

  registerUser(user){
    let headers = new HttpHeaders();
    headers.append('content-type','application/json');

    return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
          .map(response =>response.json())
          .catch(this.errorHandler)

  }


  errorHandler(error:HttpErrorResponse){
     return throwError(error.message||"Server not responding");
  }

}

ฉันยังนำเข้าคุณสมบัติแผนที่แบบนี้ด้วย:

import {map} from 'rxjs/add/operator';

ข้อผิดพลาด:

Property 'map' does not exist on type 'Observable<Object>'

ผู้ใช้คือวัตถุ

คำตอบ #1

ถ้าคุณกำลังใช้ RXJS 6 หรือสูงกว่า วิธีการใช้ตัวดำเนินการก็มีการเปลี่ยนแปลงเล็กน้อย

คุณนำเข้าด้วย:

import { map, catchError } from 'rxjs/operators';

คุณใช้ฟังก์ชัน map ภายในตัวดำเนินการ pipe แบบนี้:

return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
      .pipe(
          map(response => {
              // doSomething 
          }),
          catchError(error => {
              this.errorHandler(error);
              return of(`Caught an error: ${error}`);
          })
      );

คำตอบ #2

  • ตั้งแต่ RxJS เวอร์ชัน 6 เป็นต้นไป การสนับสนุนการเรียกตัวดำเนินการโดยตรงบน Observable ถูกเลิกใช้แล้ว แทนที่จะใช้ Observable.pipe
  • ตั้งแต่ RxJS เวอร์ชัน 6 เป็นต้นไป การสนับสนุนการนำเข้า operators โดยตรงถูกยกเลิก แทนที่จะใช้ ให้ทำการนำเข้าจาก rxjs/operators
  • HttpClient (จาก @angular/common/http) โดยค่าเริ่มต้นจะแปลงการตอบสนองเป็น JSON ไม่จำเป็นต้องใช้ตัวดำเนินการ map (นี่คือพฤติกรรมเดิมสำหรับ Http (จาก @angular/http))

ดูตัวอย่างที่แก้ไขแล้วด้านล่าง:

import { /* imports go here */ } from '@angular/common/http';
// ...

// ...
export class AuthService {
  // ...

  registerUser(user){
    let headers = new HttpHeaders();
    headers.append('content-type','application/json');

    return this.http.post('http://localhost:8080/users/register',user,{headers:headers})
          .catch(this.errorHandler);

  }
}