【问题标题】:unable to subscribe the observable in angular无法以角度订阅 observable
【发布时间】:2021-01-20 05:18:54
【问题描述】:

我是 rxjs 的新手。我已经阅读了 angular 的文档并在 ts 文件中尝试了 rxjs 的基本概念。 不幸的是,它给了我一个错误。我的代码如下:

import { Component } from '@angular/core';
import { of, pipe } from 'rxjs';
import { filter, map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Rxtest';
  squareOdd = of(1, 2, 3, 4, 5)
  .pipe(
    filter(n => n % 2 !== 0),
    map(n => n * n)
  );
  squareOdd.subscribe(x => console.log(x));

}

编译后我遇到的错误如下: src/app/app.component.ts(17,3) 中的错误:错误 TS2300:重复标识符“squareOdd”。 src/app/app.component.ts(17,3):错误 TS2717:后续属性声明必须具有相同的类型。属性“squareOdd”必须是“Observable”类型,但这里有“any”类型。 src/app/app.component.ts(17,40):错误 TS2304:找不到名称“x”。

【问题讨论】:

  • 尝试将订阅移动到contsructor或ngOnInit() {...}

标签: angular rxjs


【解决方案1】:

根据您的要求将您的逻辑移动到诸如 ngOnInit、构造函数方法或任何自定义方法之类的方法中。在任何类原型方法或构造方法中添加逻辑。 例如在你的情况下:

import { Component } from '@angular/core';
import { of, pipe } from 'rxjs';
import { filter, map } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Rxtest';
  squareOdd = of(1, 2, 3, 4, 5)
  .pipe(
    filter(n => n % 2 !== 0),
    map(n => n * n)
  );

  ngOnInit() {
    this.squareOdd.subscribe(x => console.log(x));
  }

}

这里定义了实例成员squareOdd,并在初始化时创建了订阅。

阅读关于 ngOnInit here

要了解更多关于 Javascript 类的信息,请阅读Here

【讨论】:

  • 谢谢,它成功了。想到 rxjs 让我忘记了语句执行。
猜你喜欢
  • 2021-09-02
  • 2017-11-26
  • 1970-01-01
  • 2019-06-26
  • 2019-04-28
  • 1970-01-01
  • 2019-12-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多