use*_*841 2 typescript angular
可能是我误会了angular的changeDetection策略。
这是说明:
onPush变更检测策略注册。loading在进行HTTP服务调用时使用文本,然后在ngIf使用原始变量完成使用后删除文本this.loading=true/false现在我的问题是,当App最初加载时,我可以loading...在S2小部件上看到文本,然后填充数据。
但是,当我单击notify siblingS1中的按钮时,它确实触发了服务调用,但是在http处理过程中,我看不到loading...文本。
这是S1的代码:
import { Component, OnInit } from '@angular/core';
import { MessagingService } from '../messaging.service';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
constructor(private _sendMessage: MessagingService) { }
ngOnInit() {
}
notifyChild() {
this._sendMessage.notifySibling();
}
}
Run Code Online (Sandbox Code Playgroud)
这是S2的代码:
import { Component, OnInit,ChangeDetectionStrategy ,ChangeDetectorRef} from '@angular/core';
import { MessagingService } from '../messaging.service';
import { switchMap, takeUntil, delay } from 'rxjs/operators';
import { of } from 'rxjs';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChildComponent implements OnInit {
public loading = true;
public myData: any;
constructor(private _receiveMessage: MessagingService,private cd: ChangeDetectorRef) { }
ngOnInit() {
this._receiveMessage.registerNotification().pipe(
switchMap(res => {
this.loading = true;
/** Simulate http call below */
return of([res.data]).pipe(
delay(5000)
)
})
).subscribe(response => {
this.myData = response;
this.loading = false;
this.cd.markForCheck();
})
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我已添加this.cd.markForCheck();订阅。如果我像这样评论我只是看到loading...而没有数据显示
讯息服务:
import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MessagingService {
public _notify = new BehaviorSubject({ data: "initial Call" });
public notify = this._notify.asObservable();
constructor() { }
notifySibling() {
this._notify.next({ data: 'call from sibling' });
}
registerNotification() {
return this.notify;
}
}
Run Code Online (Sandbox Code Playgroud)
完整的工作示例已发布在stackblitz上
OnPush仅当@Input属性更改时,策略运行检查才能运行,如果要在异步上下文中运行它,则必须this.cd.markForCheck()在请求之前和请求之后调用自己。
ngOnInit() {
this._receiveMessage.registerNotification().pipe(
switchMap(res => {
this.loading = true;
/** note this */
this.cd.markForCheck();
return of([res.data]).pipe(
delay(1000)
)
})
).subscribe(response => {
this.myData = response;
this.loading = false;
this.cd.markForCheck();
})
}
Run Code Online (Sandbox Code Playgroud)
https://stackblitz.com/edit/angular-pmvmgz
英语不是我的母语:(
| 归档时间: |
|
| 查看次数: |
532 次 |
| 最近记录: |