Angular HTTP GET with TypeScript error http.get(…).map is not a function in [null]

前端 未结 19 2444
时光取名叫无心
时光取名叫无心 2020-11-22 03:36

I have a problem with HTTP in Angular.

I just want to GET a JSON list and show it in the view.

Service class

im         


        
相关标签:
19条回答
  • 2020-11-22 04:06

    True, RxJs has separated its map operator in a separate module and now you need to explicity import it like any other operator.

    import rxjs/add/operator/map;

    and you will be fine.

    0 讨论(0)
  • 2020-11-22 04:11

    import { map } from 'rxjs/operators';

    this works for me in angular 8

    0 讨论(0)
  • 2020-11-22 04:12

    Using Observable.subscribe directly should work.

    @Injectable()
    export class HallService {
        public http:Http;
        public static PATH:string = 'app/backend/'    
    
        constructor(http:Http) {
            this.http=http;
        }
    
        getHalls() {
        // ########### No map
               return this.http.get(HallService.PATH + 'hall.json');
        }
    }
    
    
    export class HallListComponent implements OnInit {
        public halls:Hall[];
        / *** /
        ngOnInit() {
            this._service.getHalls()
               .subscribe(halls => this.halls = halls.json()); // <<--
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:12

    I have a solution of this problem

    Install this package:

    npm install rxjs@6 rxjs-compat@6 --save
    

    then import this library

    import 'rxjs/add/operator/map'
    

    finally restart your ionic project then

    ionic serve -l
    
    0 讨论(0)
  • 2020-11-22 04:13

    From rxjs 5.5 onwards, you can use the pipeable operators

    import { map } from 'rxjs/operators';
    

    What is wrong with the import 'rxjs/add/operator/map';

    When we use this approach map operator will be patched to observable.prototype and becomes a part of this object.

    If later on, you decide to remove map operator from the code that handles the observable stream but fail to remove the corresponding import statement, the code that implements map remains a part of the Observable.prototype.

    When the bundlers tries to eliminate the unused code (a.k.a. tree shaking), they may decide to keep the code of the map operator in the Observable even though it’s not being used in the application.

    Solution - Pipeable operators

    Pipeable operators are pure functions and do not patch the Observable. You can import operators using the ES6 import syntax import { map } from "rxjs/operators" and then wrap them into a function pipe() that takes a variable number of parameters, i.e. chainable operators.

    Something like this:

    getHalls() {
        return this.http.get(HallService.PATH + 'hall.json')
        .pipe(
            map((res: Response) => res.json())
        );
    }
    
    0 讨论(0)
  • 2020-11-22 04:17

    Global import is safe to go with.

    import 'rxjs/Rx';

    0 讨论(0)
提交回复
热议问题