【问题标题】:Angular won't import Rxjs showing errorAngular 不会导入显示错误的 Rxjs
【发布时间】:2018-11-20 10:42:24
【问题描述】:

我在我的 Angular 应用程序中从 db 导入数据时遇到问题,确切地说,我认为我的代码是正确的,但我在导入 Rxjs 时遇到问题。我将在这里发布我的代码:

import {Component, Directive} from '@angular/core';
import {FormGroup, FormControl} from '@angular/forms';
import {Http, Response, Headers} from '@angular/http';
import {Router, ActivatedRoute, Params} from '@angular/router';
import 'rxjs/Rx';

@Component({
    selector: 'app-room',
    templateUrl: './room.component.html',
    styleUrls: ['./room.component.css']
})
export class classRoomComponent {
    public sobe: any = [];
    http: Http;
    router: Router;
    route: ActivatedRoute;
    data: Object[];
    public id: Number;

    constructor(route: ActivatedRoute, http: Http, router: Router) {
        this.http = http;
        this.router = router;
        this.route = route;
    }

    ngOnInit() {

        this.route.params.subscribe((params: Params) => {
            let id = params['id'];
            let headers = new Headers();
            headers.append('Content-Type', 'application/x-www-form-urlencoded');
            headers.append("token", localStorage.getItem("token"));
            this.http.get('http://localhost/hotel/getroom.php?id=' + id, {headers: headers}).map(res => res.json()).share().subscribe(data => {
                    this.data = data.data;
                },
                err => {
                    this.router.navigate(['./']);
                }
            );
        });
    }
}

我哪里出错了,我该怎么做才能获取数据?或修复导入

ps 这是我为 rxjs 得到的错误: “可观察”类型上不存在属性“地图”。

【问题讨论】:

  • 如果你使用的是rxjs6+,请参考stackoverflow.com/questions/50340749/…
  • 是的,我相信 6.0
  • 如果你使用 rxjs 6 你需要使用管道操作符 pipe(map(() => {}))
  • 和导入什么管道?
  • 并只导入你需要的东西而不是所有的'rxjs',在这种情况下,你需要的所有东西(如我所见)来自'rxjs/operators'import { map } from 'rxjs/operators'map运算符

标签: angular rxjs


【解决方案1】:

在 rxjs6+ 中,您需要使用 pipeable operators,您可以从 'rxjs/operators' 导入它们,在您的情况下,您只需要 mapshare 运算符,因此您的解决方案将如下所示:

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

然后在代码中使用

this.http.get('http://localhost/hotel/getroom.php?id='+id,{headers:headers})
    .pipe(
        map(res => res.json()),
        share()
    )
    .subscribe(() => {})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-06
    • 2022-12-21
    • 1970-01-01
    • 2019-01-12
    • 2019-01-19
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多