我正在尝试使用计时器绘制值,以便每x秒对api进行一次调用 在订阅中,我无法访问angular属性 我尝试在方法中使用const,但是它也不起作用。
import { Component, OnDestroy, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { timer, of, Observable, Subject } from 'rxjs';
import { switchMap, takeUntil, catchError } from 'rxjs/operators';
import { APIService } from './api.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class AppComponent implements OnDestroy, OnInit {
name = 'Angular 6';
text:string ;
constructor(private apiService: APIService) { }
// Kill subject to stop all requests for component
private killTrigger: Subject<void> = new Subject();
private refreshInterval$: Observable<any> = timer(0, 1000)
.pipe(
// This kills the request if the user closes the component
takeUntil(this.killTrigger),
// switchMap cancels the last request, if no response have been received since last tick
switchMap(() => this.apiService.getContacts()),
// catchError handles http throws
catchError(error => of('Error'))
);
ngOnInit() {
const that = this;
this.refreshInterval$.subscribe(data=>{
this.text = 'bye';
//this not appear in the template
debugger;
console.log(this.text);
});
}
ngOnDestroy(){
this.killTrigger.next();
}
}
//模板
<p>
Status After Interval: {{ text}}
</p>