首先,我们需要安装Angular和rxjs。打开命令行,导航到你的Angular项目根目录,并运行以下命令:
npm install @angular/core @angular/common @angular/cli rxjs --save
接下来,我们可以开始编写代码示例。
import { Component } from '@angular/core';
import { Subject } from 'rxjs';
import { debounceTime, distinctUntilChanged } from 'rxjs/operators';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
private themeSubject: Subject = new Subject();
public theme$: Observable = this.themeSubject.asObservable();
public message: string = '';
constructor() {
this.theme$.pipe(
debounceTime(300),
distinctUntilChanged()
).subscribe((theme: boolean) => {
if (theme) {
// 应用私有主题
} else {
// 应用公共主题
}
});
}
public toggleTheme(): void {
this.themeSubject.next(true);
}
}
这样,当你点击按钮时,toggleTheme()方法将会被调用,私有主题将会被应用。同时,当你在文本框中输入消息时,该消息将通过rxjs的管道流到theme$可观察对象,然后在组件的构造函数中订阅该可观察对象,以便在消息改变时执行相应的操作。