Что делать для запуска функции сразу после ngoninit в angular 5
Это касается крючков жизненного цикла. Мое требование состоит в том, чтобы запустить функцию - фон только после инициализации страницы. Я использовал ngAfterViewInit(). но он не ожидает массива, который находится в ngoninit().
export class Parent2Component implements OnInit , DoCheck {
constructor(private getHTTP: HttpCallService) { }
eventResults: any;
apiParam: any = ['posts', 'albums', 'comments', 'photos', 'users',
'todos', 'posts', 'albums', 'comments', 'photos', 'users', 'todos',
'posts', 'albums', 'comments', 'photos', 'users', 'todos', 'posts',
'albums', 'comments', 'photos', 'users', 'todos'];
resultArray: any = [];
finalArray: any = [];
displayedColumns: string[] = ['resourceId'];
finalObject: any = [];
demoObject: any = [];
getCatagory(index) {
this.demoObject = this.demoData.resources.webcast[index];
console.log('this.demoObject' , this.demoObject);
}
getEventsData() {
for (let index = 0; index < this.apiParam.length; index++) {
this.getHTTP.getData('https://jsonplaceholder.typicode.com/' +
this.apiParam[index])
.subscribe((response) => {
this.eventResults = response;
console.log('All Data of ' + this.apiParam[index] + 'is ' +
this.eventResults);
});
}
}
getDemo() {
this.demoObject = this.demoData.resources.webcast[0];
this.getHTTP
.getData('https://jsonplaceholder.typicode.com/posts' )
.subscribe((respData) => {
console.log('================Resp init====================');
console.log(respData);
});
}
getObs() {
const apiRoot = 'https://jsonplaceholder.typicode.com/';
const urls = [];
for (let i = 0; i < this.apiParam.length; i++) {
urls.push(apiRoot + this.apiParam[i]);
}
of(...urls).pipe(
concatMap((url: string) => this.getHTTP.getData(url)))
.subscribe((result) => {
this.resultArray.push(result);
// console.log('this.resultArray', this.resultArray);
if (this.resultArray.length === this.apiParam.length) {
for (let index = 0; index < this.resultArray.length; index++) {
// console.log(this.apiParam[index]);
this.finalObject = { [this.apiParam[index]]:
this.resultArray[index] };
this.finalArray.push(this.finalObject);
}
}
});
console.log('========this.finalArray============================');
console.log(this.finalArray);
// console.log('====================================');
}
ngOnInit() {
console.log('ONinit');
this.getDemo();
}
ngDoCheck() {
console.log('AfterONinit');
this.getObs();
}
}
- Если я использую ngDocheck(), код входит в бесконечный цикл. И ngViewinit не вписывается в эту ситуацию. Помогите мне
1 ответ
Как я вижу, вам нужен getDemo, вызываемый из ngonit, чтобы быть успешным / завершенным и вызывать getObs(). Просто вызовите getObs внутри функции обратного вызова getDemo:
getDemo() {
this.demoObject = this.demoData.resources.webcast[0];
this.getHTTP
.getData('https://jsonplaceholder.typicode.com/posts' )
.subscribe((respData) => {
console.log('================Resp init====================');
console.log(respData);
this.getObs(); // Add this here and you will get your expected behaviour of getting the result array before calling getObs
});
}