Ngoninit Not Being Called When Injectable Class Is Instantiated

ngOnInit not being called when Injectable class is Instantiated

Lifecycle hooks, like OnInit() work with Directives and Components. They do not work with other types, like a service in your case. From docs:

A Component has a lifecycle managed by Angular itself. Angular creates it, renders it, creates and renders its children, checks it when its data-bound properties change and destroy it before removing it from the DOM.

Directive and component instances have a lifecycle as Angular creates, updates, and destroys them.

Component ngOninit model bind issue

If you want to use the | async pipe it will only work on an Observable.

In your case this.objName is not an observable. this.objName is a value from property Firstname on object j which was emitted. You are trying to treat a single value as an observable - that's not how this works. Follow my example for better understanding on this.

Also try to use camelCase instead of PascalCase when naming properties (e.g FirstName to firstName).

<div>
{{ objName$ | async }}
<br />
<br />
<ng-container *ngIf="objName$ | async as obj">
{{ obj.FirstName }}
</ng-container>
</div>
@Component({
selector: 'async-pipe',
templateUrl: './async-pipe.component.html',
styleUrls: ['./async-pipe.component.css'],
})
export class AsyncPipeComponent implements OnDestroy, OnInit {

objName$: Observable<any>;
unsubscribe$: Subject<void> = new Subject<void>();

ngOnDestroy() {
this.unsubscribe$.next();
this.unsubscribe$.complete();
}

ngOnInit() {
this.objName$ = this.getAsyncData().pipe(takeUntil(this.unsubscribe$));
}

getAsyncData() {
// Fake Slow Async Data
return of({
FirstName: 'Luke',
LastName: 'Skywalker',
}).pipe(delay(2000));
}
}

Working example: https://stackblitz.com/edit/async-pipe-8c2brn?file=app%2Fasync-pipe%2Fasync-pipe.component.ts

Angular 2 ngOnInit not called

I guess it's a zone issue.

Inject NgZone (import from angular2/core

constructor(private zone:NgZone) {}

this._browser.getStorageValue('api_key', api_key => {
if (api_key) {
this.zone.run(() => this._browser.gotoMain());
}
})

ngOnInit not called when same component is loaded with different data

Inject the route and subscribe to parameters change

constructor(route:ActivatedRoute) {
route.params.forEach(params => {
myInit(params['paramId']);
});
}

ngOnInit() not being invoked - even first time running the Ionic app

This was due to the GoogleVoice extension. After disabling the extension the ngOnInit() proceeded correctly



Related Topics



Leave a reply



Submit