繁体   English   中英

无法以角度订阅 observable

[英]unable to subscribe the observable in angular

我是 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”。

根据您的要求,将您的逻辑移动到诸如 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并在 init 上创建了订阅。

在此处阅读 ngOnInit

要了解有关 Javascript 类的更多信息,请阅读此处

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM