如果你遇到了“Angular Observable - 订阅但是HTML没有输出信息”的问题,可能有以下几种解决方法:
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-example',
template: `
{{ data }}
`
})
export class ExampleComponent {
data: string;
ngOnInit() {
const observable$ = new Observable((observer) => {
observer.next('Hello World');
observer.complete();
});
observable$.subscribe((value) => {
console.log(value); // 检查Observable是否发出了值
this.data = value;
});
}
}
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-example',
template: `
{{ data$ | async }}
`
})
export class ExampleComponent {
data$: Observable;
ngOnInit() {
this.data$ = new Observable((observer) => {
observer.next('Hello World');
observer.complete();
});
}
}
ChangeDetectorRef
的detectChanges()
方法来更新视图。import { Component, ChangeDetectorRef } from '@angular/core';
import { Observable } from 'rxjs';
@Component({
selector: 'app-example',
template: `
{{ data }}
`
})
export class ExampleComponent {
data: string;
constructor(private cdRef: ChangeDetectorRef) {}
ngOnInit() {
const observable$ = new Observable((observer) => {
observer.next('Hello World');
observer.complete();
});
observable$.subscribe((value) => {
this.data = value;
this.cdRef.detectChanges(); // 手动更新视图
});
}
}
通过检查Observable是否发出值,正确使用async管道或手动更新视图,你应该能够解决“订阅但是HTML没有输出信息”的问题。