我是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”的类型必须为“可观察”,但此处的类型为“任何”。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上创建了预订。
要了解有关Javascript类的更多信息,请阅读此处
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句