У меня есть следующий код:
clickEventsubscription: Subscription;
constructor(
private activatedRoute: ActivatedRoute,
private newsService: NewsService,
private app: AppComponent,
private EventlistenerService: EventlistenerService,
public modalController: ModalController
) {
this.clickEventsubscription = this.EventlistenerService.getClickEvent().subscribe(() => {
this.update();
});
}
update() {
this.resetParameters();
this.ngOnInit();
}
Я хочу дождаться сброса параметров(); завершена, а затем вызовите ngOnInit(); или какой-либо другой класс, потому что я хочу сначала сбросить параметры, чтобы загрузка, но параметры не были сброшены...
Вот мой полный код:
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';
import { IonInfiniteScroll } from '@ionic/angular';
import { ModalController } from '@ionic/angular';
import { ArticlePage } from '../article/article.page';
import { NewsService } from '../services/news.service';
import { AppComponent } from '../app.component';
import { EventlistenerService } from '../services/eventlistener.service';
@Component({
selector: 'app-folder',
templateUrl: './folder.page.html',
styleUrls: ['./folder.page.scss'],
})
export class FolderPage implements OnInit {
@ViewChild(IonInfiniteScroll, { static: true }) infiniteScroll: IonInfiniteScroll;
clickEventsubscription: Subscription;
public folder: string;
data: any;
page = 1;
private country: string = '';
private category: string = '';
public search: string = '';
public showInfiniteScroll: boolean = true;
private language: string;
private from: string;
private to: string;
private sortBy: string;
constructor(
private activatedRoute: ActivatedRoute,
private newsService: NewsService,
private app: AppComponent,
private EventlistenerService: EventlistenerService,
public modalController: ModalController
) {
this.clickEventsubscription = this.EventlistenerService.getClickEvent().subscribe(() => {
this.update();
});
}
update() {
this.resetParameters();
this.ngOnInit();
}
ngOnInit() {
this.folder = this.activatedRoute.snapshot.paramMap.get('id');
this.checkCountry();
this.checkCategory();
this.checkSelectionInEverything();
this.loadData();
}
checkCountry() {
this.country = this.app.getCountry();
}
checkCategory() {
this.category = this.app.getCategory();
}
checkSelectionInEverything() {
this.language = this.app.getLanguage();
this.from = this.app.getFrom();
this.to = this.app.getTo();
this.sortBy = this.app.getSortBy();
}
loadData() {
if (this.search != '' || this.folder == 'top-headlines') {
this.newsService.getData(this.folder, this.country, this.category, this.search, this.page, this.language, this.from, this.to, this.sortBy).subscribe(data => {
// initial load of the data
console.info(this.page);
console.info(this.clickEventsubscription);
if (this.page == 1) {
this.data = data;
console.info(data);
}
// append next articles to the data array
else {
let arr: any[] = data['articles'];
for (let i = 0; i < data['articles'].length; i++) {
this.data.articles.push(arr[i]);
}
this.checkIfAllArtriclesAreLoaded();
}
});
}
}
moreData(event) {
this.page++;
this.loadData();
setTimeout(() => {
event.target.complete();
// App logic to determine if all data is loaded
// and disable the infinite scroll
}, 500);
}
doRefresh(event) {
this.resetParameters();
this.loadData();
setTimeout(() => {
event.target.complete();
});
}
resetParameters() {
this.data = null;
this.page = 1;
this.country = '';
this.category = '';
this.search = '';
this.language = '';
this.sortBy = '';
this.from = null;
this.to = null;
this.showInfiniteScroll = true;
}
checkIfAllArtriclesAreLoaded() {
if (this.data['articles'].length >= this.data.totalResults) this.showInfiniteScroll = false;
}
async presentModal(article) {
this.newsService.currentArticle = article;
const modal = await this.modalController.create({
component: ArticlePage,
cssClass: 'my-custom-class'
});
return await modal.present();
}
}
А вот код из моего EventListenerService:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class EventlistenerService {
private subject = new Subject<any>();
sendClickEvent() {
this.subject.next();
}
getClickEvent(): Observable<any> {
return this.subject.asObservable();
}
}
@Ashu да, нужно полностью вызвать
так в чем проблема, если он работает полностью?
Я думаю, что resetParametes работает медленно или не работает, вероятно, потому что я загружаю данные в ngOnInit только в том случае, если страница параметров == 1, но если я регистрирую это, страница всегда на 2 или выше ... @Ashu
Проблема в другом. Я не знаю, почему вы пытаетесь добиться этого, но вызывать ngOnInit()
в своем коде — ужасная идея. Angular дает вам информацию о том, когда компонент инициализируется, вы не можете заставить компонент инициализировать себя в данный момент. Возможно, вы захотите использовать другую функцию init()
со стратегией обнаружения изменений OnPush
.
@Marco Я обновил функцию update(), чтобы она не вызывала ngOnInit(), но все равно не работает :(
ngOnInit вызывается только один раз при создании экземпляра директивы. Вы можете переместить код внутри ngOnInit в другую функцию и вместо этого вызвать ее;
Я обновил свой код, который я вызываю в другой функции, но все еще не работает
Вы где-то вызываете метод sendClickEvent?
да, я называю это другим методом, и это должно работать :)
Да, это была проблема :), но вчера он не полностью обновил ионную подачу, поэтому я не видел изменений на веб-сайте: / THX
resetParameters — это синхронная функция, которая должна быть полностью запущена до вызова ngOnInit?