我的应用程序结构如下,我的问题是如何在接收初始或将来的数据时更新子组件视图,假设我只有一个具有事件OnDataUpdate的服务,所有子组件都在接收该服务的同一实例另一方面,由于它已在“应用程序模块提供程序”部分中声明,因此我尝试了所有这些方法,但均无效:
@Injectable()
export class ApiService {
public OnDataRecieved: EventEmitter<Model> = new EventEmitter<Model>();
constructor(private http: HttpClient, private ngZone: NgZone) {
}
public getDataAsync(): Observable<Model> {
return this.http
.get<Model>('url')
.pipe(catchError(er => throwError(er)));
}
}
在App根组件中,这类似于下面的代码
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
changeDetection: ChangeDetectionStrategy.Default
})
export class AppComponent implements DoCheck {
model: BehaviorSubject<Model> = new BehaviorSubject<Model>(new Model()); //with default values
subModel: BehaviorSubject<SubModel>;
constructor(private apiService: ApiService,
private zone: NgZone) {
this.apiService.getDashboard().subscribe((data) => {
this.zone.run(() => {
this.apiService.OnDataReceived.emit(data);
this.model = new BehaviorSubject<Model>(data);
});
});
this.model.subscribe((mdl) => {
this.subModel = new BehaviorSubject<SubModel>(mdl.subModel));
});
}
ngDoCheck() {
}
}
想象当数据被加载或更改时,模型是通过子组件嵌套和传播的,其结构可以像这样
__ AppRootComponent
|_____ Component1
|_________SubCompoent1-1
|_________SubCompoent1-2
|_____ Component2
|_________SubCompoent2-1
|____________SubCompoent2-1-1
我在ngDoCheck中接收到数据更改,无需触发检测更改,但是UI和子组件未更新!
答案 0 :(得分:1)
我意识到了如何解决该问题,这些组件的结构是分层的,并且我通过@Input()传递了每个组件的模型,问题是初始请求是异步的,并且在接收真正的父对象之前呈现了这些组件对象,并且从服务器接收到父对象后,传递的Input对象没有对象引用,因此它们将无法获取更改。
那么,我们如何解决这个问题?简单!删除所有输入并使用事件驱动的编程 怎么样?为每个对象创建一个事件,或为所有其他对象所依赖的父(根)对象创建一个事件,在全局服务中共享事件,在收到根对象后触发/发出事件,并在子组件中订阅该事件。让我在下面向您展示一个简单的代码段:
import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { Injectable, EventEmitter } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { RootDto } from 'src/app/model/root.dto.model';
@Injectable()
export class CoreApiService {
public onDataReceived: EventEmitter<RootDto> = new EventEmitter<RootDto>();
constructor(private http: HttpClient) {
}
public getRootObject(objectId: number): Observable<RootDto> {
// const _params = new HttpParams().set('objectId', objectId);
return this.http
.get<RootDto>(`${Constants.ApiUrl}/root/${objectId}`)
.pipe(catchError((err: HttpErrorResponse) => {
return throwError(err);
}));
}
}
根分量如下所示
import {
Component,
OnInit
} from '@angular/core';
import { CoreApiService } from './core/services/core-api.service';
import { RootDto } from 'src/app/model/root.dto.model';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
constructor(private apiService: CoreApiService) {
}
ngOnInit() {
this.apiService.getRootObject().subscribe((data: RootDto) => {
// todo: do something here
this.apiService.onDataReceived.emit(data);
},
(err: HttpErrorResponse) => {
if (err.status === 401 || err.status === 403) {
// not authorized
}else {
// todo: error happened!
}
}
);
}
}
子组件如下所示
import {
Component,
OnInit,
NgZone
} from '@angular/core';
import { CoreApiService } from '../core/services/core-api.service';
import { RootDto } from 'src/app/model/root.dto.model';
import { ChildDto } from '../model/child.dto.model';
@Component({
selector: 'app-first-child',
templateUrl: './firstChild.component.html',
styleUrls: ['./firstChild.component.css']
})
export class FirstChildComponent implements OnInit {
dto: ChildDto;
isLoaded = false;
constructor(private apiService: CoreApiService, private zone: NgZone) {
this.apiService.onDataReceived.subscribe((rootDto: RootDto) => {
this.zone.run(() => {
this.dto = Utils.ObjectFactory.Create(rootDto.firstChildDto); // to make sure that we will have a new reference (so that change detction will be triggered) i use object instantiation
// NOTICE:
// for arrays don't simply assign or push new item to the array, because the reference is not changed the change detection is not triggered
// if the array size is small before assigning new value, you can simply empty (myArray = [];) the array otherwise don't do that
this.isLoaded = true;
});
});
}
ngOnInit() {
}
// the rest of logic
}
您可以对所有其他组件执行相同的操作,甚至可以在共享服务中创建更多事件并根据需要触发它
答案 1 :(得分:0)
让我们从一些常规建议开始:
通常不需要服务即可使数据从组件流到其(大)子级。为此使用@Input
绑定。
使用服务管理数据流时,请使用普通RxJS,即Observable
,Subject
,BehaviorSubject
等的实例。EventEmitter
是一个Angular专门用于处理组件和指令的输出事件。如果您想使用BehaviorSubject
查看类似的解决方案,请选中this answer。
您不需要告诉Angular在默认区域中运行代码。默认情况下会执行此操作。
具体来说,您的服务可以像以下这样简单:
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
getData(): Observable<Model> {
return this.http.get<Model>('...');
}
}
然后,组件可以订阅它并将值存储在纯同步属性中。可以将此属性作为@Input()
传递给子组件:
@Component({
selector: 'my-app',
template: `
<strong>AppComponent:</strong> {{model | json}}
<child [model]="model"></child>
`
})
export class AppComponent implements OnInit {
model: Model;
constructor(private apiService: ApiService) { }
ngOnInit(): void {
this.apiService.getData()
.subscribe(model => this.model = model);
}
}
您还可以随时更新model
属性,并且更改将传播到子代和子代组件。
Here's a Stackblitz和示例实现。