Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ionic v2 - Loading Service - Throwing error "cannot read property 'nativeElement' ..." #6209

Closed
tonyawad88 opened this issue Apr 17, 2016 · 53 comments
Assignees
Milestone

Comments

@tonyawad88
Copy link

Short description of the problem:

I have a welcome page that invokes the Loading service in its constructor. As soon as the page loads for the first time the error / exception is thrown.

What behavior are you expecting?

No exceptions thrown.

Steps to reproduce:

  1. Create a new ionic project ionic start MyIonic2Project tutorial --v2 --ts
  2. On the root page, add in its constructor the following:
import {Page,Loading,NavController} from 'ionic-angular';
@Page({
  templateUrl: 'build/pages/hello-ionic/hello-ionic.html'
})
export class HelloIonicPage {
  constructor(private nav: NavController) {
    this.nav =nav;
    let loading = Loading.create({
      content: "Please wait...",
      duration: 3000,
      dismissOnPageChange: true
    });
    this.nav.present(loading);
  }
}

3 . Check the console for the exception

Other information: (e.g. stacktraces, related issues, suggestions how to fix, stackoverflow links, forum links, etc)

browser_adapter.ts:73 STACKTRACE:BrowserDomAdapter.logError @ browser_adapter.ts:73ExceptionHandler.call @ exception_handler.ts:52(anonymous function) @ application_ref.ts:258schedulerFn @ async.ts:127SafeSubscriber.__tryOrUnsub @ Subscriber.js:166SafeSubscriber.next @ Subscriber.js:115Subscriber._next @ Subscriber.js:74Subscriber.next @ Subscriber.js:51Subject._finalNext @ Subject.js:124Subject._next @ Subject.js:116Subject.next @ Subject.js:73EventEmitter.emit @ async.ts:113NgZone._zoneImpl.ng_zone_impl_1.NgZoneImpl.onError @ ng_zone.ts:134NgZoneImpl.inner.inner.fork.onHandleError @ ng_zone_impl.ts:88ZoneDelegate.handleError @ angular2-polyfills.js:336Zone.runGuarded @ angular2-polyfills.js:244NgZoneImpl.runInner @ ng_zone_impl.ts:97NgZone.run @ ng_zone.ts:204NavController._afterTrans @ nav-controller.js:1003(anonymous function) @ nav-controller.js:979Animation._didFinish @ animation.js:590Animation.play @ animation.js:264(anonymous function) @ nav-controller.js:990ZoneDelegate.invoke @ angular2-polyfills.js:332Zone.run @ angular2-polyfills.js:227NgZoneImpl.runOuter @ ng_zone_impl.ts:98NgZone.runOutsideAngular @ ng_zone.ts:218NavController._beforeTrans @ nav-controller.js:948NavController._postRender @ nav-controller.js:930(anonymous function) @ nav-controller.js:865(anonymous function) @ nav-controller.js:1217promiseReactionJob @ es6-shim.js:2171(anonymous function) @ es6-shim.js:2159Item.run @ browser.js:64drainQueue @ browser.js:34ZoneDelegate.invokeTask @ angular2-polyfills.js:365NgZoneImpl.inner.inner.fork.onInvokeTask @ ng_zone_impl.ts:54ZoneDelegate.invokeTask @ angular2-polyfills.js:364Zone.runTask @ angular2-polyfills.js:263ZoneTask.invoke @ angular2-polyfills.js:431
browser_adapter.ts:73 TypeError: Cannot read property 'nativeElement' of undefined
    at new LoadingMdPopOut (http://localhost:8101/build/js/app.bundle.js:44356:40)
    at Function.Transition.createTransition (http://localhost:8101/build/js/app.bundle.js:63476:16)
    at http://localhost:8101/build/js/app.bundle.js:46769:58
    at ZoneDelegate.invoke (http://localhost:8101/build/js/angular2-polyfills.js:332:29)
    at Zone.run (http://localhost:8101/build/js/angular2-polyfills.js:227:44)
    at NgZoneImpl.runOuter (http://localhost:8101/build/js/app.bundle.js:26898:71)
    at NgZone.runOutsideAngular (http://localhost:8101/build/js/app.bundle.js:26817:80)
    at Portal.NavController._beforeTrans (http://localhost:8101/build/js/app.bundle.js:46759:20)
    at Portal.NavController._postRender (http://localhost:8101/build/js/app.bundle.js:46741:14)
    at Portal.NavController._render (http://localhost:8101/build/js/app.bundle.js:46657:18)
  -------------   Elapsed: 77 ms; At: Sun Apr 17 2016 13:54:49 GMT-0400 (EDT)   -------------  
    at Object.Zone.longStackTraceZoneSpec.onScheduleTask (http://localhost:8101/build/js/angular2-polyfills.js:1354:23)
    at ZoneDelegate.scheduleTask (http://localhost:8101/build/js/angular2-polyfills.js:342:50)
    at Zone.scheduleMacroTask (http://localhost:8101/build/js/angular2-polyfills.js:283:40)
    at http://localhost:8101/build/js/angular2-polyfills.js:133:26
    at setTimeout (eval at createNamedFn (http://localhost:8101/build/js/angular2-polyfills.js:973:18), <anonymous>:3:37)
    at process.nextTick (http://localhost:8101/build/js/app.bundle.js:64854:9)
    at enqueuePromiseReactionJob (http://localhost:8101/build/js/app.bundle.js:37073:7)
    at fulfillPromise (http://localhost:8101/build/js/app.bundle.js:37099:9)
  -------------   Elapsed: 52 ms; At: Sun Apr 17 2016 13:54:49 GMT-0400 (EDT)   -------------  
    at Object.Zone.longStackTraceZoneSpec.onScheduleTask (http://localhost:8101/build/js/angular2-polyfills.js:1354:23)
    at ZoneDelegate.scheduleTask (http://localhost:8101/build/js/angular2-polyfills.js:342:50)
    at Zone.scheduleEventTask (http://localhost:8101/build/js/angular2-polyfills.js:286:40)
    at zoneAwareAddEventListener (http://localhost:8101/build/js/angular2-polyfills.js:880:11)
    at XMLHttpRequest.addEventListener (eval at createNamedFn (http://localhost:8101/build/js/angular2-polyfills.js:973:18), <anonymous>:3:43)
    at XMLHttpRequest.desc.set [as onload] (http://localhost:8101/build/js/angular2-polyfills.js:776:19)
    at XHRImpl.get (http://localhost:8101/build/js/app.bundle.js:30356:20)
    at TemplateNormalizer.normalizeTemplate (http://localhost:8101/build/js/app.bundle.js:10294:30)
  -------------   Elapsed: 327 ms; At: Sun Apr 17 2016 13:54:49 GMT-0400 (EDT)   -------------  
    at Object.Zone.longStackTraceZoneSpec.onScheduleTask (http://localhost:8101/build/js/angular2-polyfills.js:1354:23)
    at ZoneDelegate.scheduleTask (http://localhost:8101/build/js/angular2-polyfills.js:342:50)
    at Zone.scheduleMacroTask (http://localhost:8101/build/js/angular2-polyfills.js:283:40)
    at http://localhost:8101/build/js/angular2-polyfills.js:133:26
    at setTimeout (eval at createNamedFn (http://localhost:8101/build/js/angular2-polyfills.js:973:18), <anonymous>:3:37)
    at process.nextTick (http://localhost:8101/build/js/app.bundle.js:64854:9)
    at enqueuePromiseReactionJob (http://localhost:8101/build/js/app.bundle.js:37073:7)
    at Promise.then (http://localhost:8101/build/js/app.bundle.js:37438:11)

Which Ionic Version? 2.x

Plunker that shows an example of your issue

http://plnkr.co/edit/fA0KB70ggJd0nptNvYpl?p=preview

Run ionic info from terminal/cmd prompt: (paste output below)

WARN: ionic.config.js has been deprecated, you can remove it.

Your system information:

Cordova CLI: 6.0.0
Gulp version:  CLI version 3.9.0
Gulp local:   Local version 3.9.1
Ionic Framework Version: 2.0.0-beta.4
Ionic CLI Version: 2.0.0-beta.25
Ionic App Lib Version: 2.0.0-beta.15
ios-deploy version: 1.8.2 
ios-sim version: 5.0.3 
OS: Mac OS X El Capitan
Node Version: v0.12.7
Xcode version: Xcode 7.3 Build version 7D175 
@ataraxus
Copy link
Contributor

Hello @tonyawad88,

are you using this Loading service, to load resources before your app starts rendering? I guess I stumbled uppon the same requirement and opened a more general question/request. Maybe you have a look and could link these issues, if they are similar to you?

#6148

@tonyawad88
Copy link
Author

@ataraxus Hii, I don't think they are related. I am able to create a barebone ionic 2 plunker and replicate the issue I am having with my app.

@adamdbradley adamdbradley self-assigned this Apr 19, 2016
@XertroV
Copy link

XertroV commented Apr 20, 2016

I have the same issue, though only when including the dismissOnPageChange: true parameter. (Does not throw an error if it's set to false)

@HereThereBeMonsters
Copy link

I encounter the same error, it seems that it happens when I try to dismiss the loading dialog "too quickly", e.g. when I get data out a cache instead of doing a HTTP request.

@jgw96
Copy link
Contributor

jgw96 commented Apr 20, 2016

Thanks for the info everyone! I am able to reproduce this and we are now looking further into this.

@keithdmoore
Copy link
Contributor

Here is a workaround that I was able to get to work:

http://plnkr.co/edit/OyGY7VVNSSAjdstr54wG?p=preview

@keithdmoore
Copy link
Contributor

I am having the same issue when trying to use the loading component at a global level. If anyone else is having trouble with that, you might consider this until this bug is resolved at least: http://www.joshmorony.com/how-to-create-a-custom-loading-component-in-ionic-2/

@keithdmoore
Copy link
Contributor

keithdmoore commented May 6, 2016

Here is a plunker that is using loading in a global way. http://plnkr.co/edit/3TfK76XpqsnUvW3dQuG3?p=preview

I had to do some trickier things in my implementation because I am using EventEmitters to indicate when an http request is started and when it has completed. Im still having a few issues with it but if I wrap the loading.dismiss() in a setTimeout, it seems to work.

@tonyawad88
Copy link
Author

tonyawad88 commented May 20, 2016

@jgw96 Hi Justin, do you have any workaround to dismiss the loading popup manually from javascript ? Calling loading.dismiss() is always throwing the 'nativeelement' error. Thanks

@jgw96
Copy link
Contributor

jgw96 commented May 20, 2016

Hey all! Can you all try with this plunker? Looks like this issue is not reproducible anymore in our latest beta.7 release! http://plnkr.co/edit/IIfn2RKAMGheD8ISVr9A?p=preview I am going to close this for now, as it seems it was fixed. But if anyone can reproduce it again with beta.7 then i will reopen. Thanks for using Ionic everyone!

@jgw96 jgw96 closed this as completed May 20, 2016
@tonyawad88
Copy link
Author

tonyawad88 commented May 20, 2016

@jgw96 I can still reproduce in beta 7. Enable the following property on Loading, and it will throw the 'native element' exception.

dismissOnPageChange: true

Any idea how to dismiss the loading from JS ? The use case in the plunker, where we use setTimeout are not too realistic. :)

I wonder if there is any event that we can emit to dismiss the "Loading" ?

Thank you !

@keithdmoore
Copy link
Contributor

keithdmoore commented May 20, 2016

@jgw96 Seems like a race condition or a digest type issue. When adding the dismissOnPageChange: true I was able to reproduce. My current hack to get around this is to do the below when displaying the loading component. I wouldn't classify this issue as fixed.

   setTimeout(()=>{
      this.nav.present(loading);
   });

@keithdmoore
Copy link
Contributor

@tonyawad88 I am using EventEmitter to handle the dismissing of the loading component.

@jgw96 jgw96 reopened this May 20, 2016
@jgw96
Copy link
Contributor

jgw96 commented May 20, 2016

Hello all, you all are correct, setting dismissOnPageChange to true makes this issue still reproducible, sorry about that! @tonyawad88 as a workaround you can use the dismiss() method on the loading component. So it would just be {{name of your loader}}.dismiss(). Hope that makes sense! I will look into this more.

@keithdmoore
Copy link
Contributor

keithdmoore commented May 20, 2016

@tonyawad88 to be more specific here is what I am doing. (currently on beta6)
In a service:

  httpRequestEventEmitter: EventEmitter<string>;
  httpResponseEventEmitter: EventEmitter<string>;

  private sendHttpRequest(request: Request, event: string): Observable<any>  {
    return Observable.of(request)
      .do((req: Request) => { this.httpRequestEventEmitter.emit(event + '-request-started'); })
      .flatMap((req: Request) => { return this.http.request(req); })
      .finally(() => {
        this.httpResponseEventEmitter.emit(event + '-request-finished');
      });
  }

In app.ts:

    this.service.httpRequestEventEmitter.subscribe(
      (data: string) => { 
          this.loading = Loading.create({
             dismissOnPageChange: true
          });
          this.app.getComponent(ROOT_NAV).present(this.loading);
      }
    );
    this.service.httpResponseEventEmitter.subscribe(
      (data: string) => { 
          this.loading.dismiss();
      }
    );

@jgw96
Copy link
Contributor

jgw96 commented May 20, 2016

@keithdmoore Just to let you know we deprecated app.getComponent in beta.7 in favor of the native Angular 2 ViewChild decorator https://angular.io/docs/ts/latest/api/core/ViewChild-var.html .

@keithdmoore
Copy link
Contributor

@jgw96 Ok. Thanks. Seems like I did see a use of ViewChild in the ionic-conference app. Thanks for the heads up! I am about to upgrade right now.

@jgw96
Copy link
Contributor

jgw96 commented May 20, 2016

No problem! Let me know how the beta.7 update goes for you! Here are some awesome instructions to help you with the upgrade: https://github.com/driftyco/ionic/blob/2.0/CHANGELOG.md#angular-update-to-200-rc1

@tonyawad88
Copy link
Author

tonyawad88 commented May 20, 2016

@keithdmoore @jgw96 this.loading.dismiss(); also throws the error.

It sure looks like a race. For now adding a settimeout of 500ms, around creating the "loading" prevents it from firing the exception.

Check this plunker out, if you display / hide the loading using the buttons, no exceptions occurs.
As soon as you use it inside "onPageDidEnter", it throws the exception.
http://plnkr.co/edit/GXugmXJi2qwaYQWKscqC

Thank you !

@keithdmoore
Copy link
Contributor

You might try using: ngAfterViewInit I had trouble with the onPageDidEnter

@biesbjerg
Copy link

biesbjerg commented May 21, 2016

EDIT: Scratch that, turns out I needed/could use this._navController.present(loading).then( ... ) to avoid dismissing before loading animation was done showing.

I'm getting the same error message, but in my case it happens if I do loading.dismiss() too quickly after doing this._navController.present(loading);

My request to productService.findOne() might be cached and return immediately, and that's when the exeption is thrown.

    public ngOnInit(): void {
        let loading = Loading.create({
            content: 'Loading...'
        });
        this._navController.present(loading);

        console.log('before loading', this._navParams.data.id);

        //this._productService.clearCache();
        this._productService
            .findOne(this._navParams.data.id)
            .subscribe(
                (data) => {
                    console.log('loading success');
                    console.log(data);
                    this.product = data;
                    loading.dismiss();
                },
                (error) => {
                    console.log('Error loading product', error);
                    loading.dismiss();
                }
            );
    }

@tonyawad88
Copy link
Author

@keithdmoore same issue with "ngAfterViewInit".

@Kingwl
Copy link

Kingwl commented Jun 23, 2016

same issue

@alouane
Copy link

alouane commented Nov 28, 2016

Hi, I don't know if you had same problem like mine, I had this Cannot read property 'nativeElement' of null error too, and problem was that I had to call
this.loader = this.loadingCtrl.create({ content: "Please wait...", dismissOnPageChange: true }); this.loader.present();

Every time an event occurs. I was calling it previously inside constructor (obviously the call happens once with constructor)

Hope it helps

@risleylima
Copy link

I did many tests on the Loading Controller, and realized that to avoid this behavior, I had to create another instance of the object after call dismiss() on it.

I don't know if it's required, because the docs don't explain that, but, to do the same tests that I did, follow this steps:

1 - Create a new object and assign this to a window property (previously defined on a typescript description file, otherwise it will not compile):

window.testLoading =  this.loadingCtrl.create({
    content: 'Please wait...'
});

2- compile and load the app on browser.

3 - after that, it's simple, you have to call, on the console of the browser:

window.testLoading.present() -> the Loading will show correctly
window.testLoading.dismiss() -> the Loading will dismiss correctly

After that, if I call the present() method on window.testLoading, I get the error: Cannot read property 'nativeElement' of null.

Here is the problem. So, if I want to call the present() method again on a Loading that I had called the dismiss() method before, I will get the error above.

To call the present() method, I had to first call the loadingCtrl to create a new instance on my window.testLoading property and only after that call the present() method.

Maybe this information will help the devs to correct the error. 😄

@uzumakinaruto123
Copy link

uzumakinaruto123 commented Dec 8, 2016

Same in nightly version ! Calling present() in ionViewWillEnter . But , it does not happen everytime.

@manucorporat
Copy link
Contributor

Currently, once you call ViewController.dismiss(), that ViewControler (toast, alert, actionsheet) is invalidated, you can't use it more than once.

@WaveMeUp
Copy link

@risleylima exactly the same behavior. As a workaround you can do this: Just create loader every time you want to use it, in my case right after modal dismissed. I'm not sure how this can make an impact on memory, but I can't find another solution for now.

constructor(public navCtrl: NavController, public modalCtrl: ModalController)
{
      this.loading = this.loadingCtrl.create({ // creating loader for the first time
        content: 'Please wait'
      });
}
showFilters() {
  let profileModal = this.modalCtrl.create(ObjectsFiltersPage);
  profileModal.onDidDismiss(() => {
    console.log('closed!')
    this.loading = this.loadingCtrl.create({ // simply create loader again after dismiss
      content: 'Please wait'
    });
    this.loadData()
  });
  profileModal.present();
}

loadData() {
  this.loading.present()
  // do something
  this.loading.dismiss()
}

ionViewDidLoad() {
  this.loadData()
}

@paoesco
Copy link

paoesco commented Dec 20, 2016

I have the same problem with RC4

  constructor(
      private securityContextHolder: SecurityContextHolder,
      private loadingCtrl: LoadingController,
      private navCtrl: NavController,
      private http: Http,
      fb: FormBuilder) {

     // Other inits

      this.loader = this.loadingCtrl.create({
        content: "Please wait..."
      });

    }
    login(form: any) {
      //this.loader.present();
      if (form.valid) {
        let value = form.value;
        this.http
        .post(`${this.apiUrl}/login`, JSON.stringify(value))
        .subscribe((res: Response) => {
         // this.loader.dismiss();
          this.securityContextHolder.setCurrentUser(res.json());
          this.navCtrl.setRoot(HomePage);
        },
        (err:Response) => {
          if (err.status == 400 && err.statusText === 'user_not_enabled') {
          //  this.loader.dismiss();
            alert('Your account has not been enabled yet. Please activate it by clicking on the link provided in e-mail');
            return false;
          } else {
          //  this.loader.dismiss();
            alert('Wrong credentials');
            return false;
          }
        });
      } else {
       // this.loader.dismiss();
        alert('Required fields : email, password');
        return false;
      }

    }

This throws TypeError: Cannot read property 'nativeElement' of null at LoadingMdPopIn.init on Chrome debug console.

Thanks

paoesco pushed a commit to Hubesco/walkingdog-services that referenced this issue Dec 20, 2016
@ghost
Copy link

ghost commented Dec 20, 2016

The problem you are getting into, is the result of a wrong thread context - or as named by angular - zone or NgZone. Your this pointer can be null or even undefined, as happened to me and a number of other commenters above.

How to resolve:

My practice - which I guess is the way handling multithreaded code is intended to be - is handle callbacks from any of the following types of "services" (and any other suspicious service...):

  1. setTimeout( () => { ... }, X);
  2. http.get() ... then( () => ...
  3. almost any observable service involving a web worker silently underneath...

How to handle:

  1. import { NgZone } from '@angular/core';
  2. Inject the angular zone.js provider to the constructor( .... , private zone: NgZone, ... )
  3. In the callback function, returning from any of the above services - return to main/ui thread context by putting your code in: zone.run( () => { your callback code } );

Example:

setTimeout( 
    () =>
    {
        zone.run(
            () =>
            {
                // Your code now runs in the context of the main ui thread
            } );
    }, 100 );

paoesco pushed a commit to Hubesco/walkingdog-services that referenced this issue Dec 21, 2016
paoesco pushed a commit to Hubesco/walkingdog-services that referenced this issue Dec 21, 2016
paoesco pushed a commit to Hubesco/walkingdog-services that referenced this issue Dec 21, 2016
@pittdewaard
Copy link

Hi all, also a litte late... but: I had the same error msg and I forgot simply to resolve(result) at my Promise in the Service ;-) maybe it will help someone...

@jgw96
Copy link
Contributor

jgw96 commented Dec 29, 2016

Hello all! This has been fixed here #9747 and will be in the next release. Thanks for using Ionic!

@jgw96 jgw96 closed this as completed Dec 29, 2016
@tryadelion
Copy link

tryadelion commented Jan 20, 2017

Is this fixed on RC5? on RC4 it's still happening, not only on the promise but just creating it.

update: in RC5 still reproducing it:

EXCEPTION: Error in ./LoginPage class LoginPage - inline template:19:4 caused by: Cannot read property 'nativeElement' of null
ErrorHandler.handleError @ main.js:53150
main.js:53152 ORIGINAL EXCEPTION: Cannot read property 'nativeElement' of null
ErrorHandler.handleError @ main.js:53152
main.js:53155 ORIGINAL STACKTRACE:
ErrorHandler.handleError @ main.js:53155
main.js:53156 TypeError: Cannot read property 'nativeElement' of null
at LoadingMdPopIn.init (main.js:103022)
at OverlayPortal.NavControllerBase._trnsStart (main.js:30502)
at LoadingMdPopIn._trnsStart (main.js:30468)
at LoadingMdPopIn.Transition.start (main.js:14847)
at OverlayPortal.NavControllerBase._transition (main.js:30485)
at OverlayPortal.NavControllerBase._postViewInit (main.js:30347)
at OverlayPortal.NavControllerBase._viewTest (main.js:30434)
at OverlayPortal.NavControllerBase._nextTrns (main.js:30206)
at OverlayPortal.NavControllerBase._queueTrns (main.js:30170)
at OverlayPortal.NavControllerBase.insertPages (main.js:30028)
ErrorHandler.handleError @ main.js:53156
main.js:53159 ERROR CONTEXT:
ErrorHandler.handleError @ main.js:53159
main.js:53160 DebugContext_nodeIndex: 20_staticNodeInfo: (...)_tplCol: 4_tplRow: 19_view: CompiledTemplate.proxyViewClasscomponent: (...)componentRenderElement: (...)context: (...)injector: (...)providerTokens: (...)references: (...)renderNode: (...)source: (...)proto: Object
ErrorHandler.handleError @ main.js:53160
main.js:1279 Uncaught ViewWrappedError

@terrence0488
Copy link

terrence0488 commented Jan 22, 2017

I am able to reproduce this in RC4.0

Cordova CLI: 6.4.0
Ionic Framework Version: 2.0.0-rc.4
Ionic CLI Version: 2.1.17
Ionic App Lib Version: 2.1.7
Ionic App Scripts Version: 0.0.47
ios-deploy version: Not installed
ios-sim version: Not installed
OS: macOS Sierra
Node Version: v6.9.1
Xcode version: Xcode 8.2.1 Build version 8C1002

[What I Did]
create a Loading as a share instance within my component and initialise the instance in constructor. So, various part of the component will call the .present() and .dismiss() of the same instance of Loading.

[How It Happen]
-> call a method and present the Loading.
-> method finish the task and dismiss the Loading.
-> call another method and present the Loading.
x-> throw error. Cannot read property 'nativeElement' of null

[How I Resolve]
Do not initialise the Loading instance in constructor. Instead, initialise it every time before I .present() it.

Its not the best thing to do in term of programming practice. I hope the Ionic team will fix this.

@RobertBroersma
Copy link

I'm experiencing the same issue with opening an action sheet. If I try to open the same instance for a second time I get the cannot read property nativeelement of null error. Workaround is to create a new instance everytime I want to present it. Which seems like a bad idea, but I don't know how to solve it otherwise.

@danielsogl
Copy link
Contributor

Same problem with elements in [ngSwitch] switching by ion-segment component

@lucaspalencia
Copy link

Updated to version 2.0.1 and still with the error, I have a method in my service with this code:

this.loading.present();
this.http.post(this.loginUrl, JSON.stringify(requestBody), {headers: headers})
 .toPromise()
 .then(response => {
    this.auth.authLogin(type, userInfo.usuario, response.json().token);
 })
 .catch(response => {
    this.loading.dismiss();
 });

The first time that my http.post executed this.loading.dismiss(); everything works ok, but if i try again the console returns the error:

Cannot ready property 'nativeElement' of null

Some help?

@malick7
Copy link

malick7 commented Mar 1, 2017

@lucaspalencia
I re-initialized the loading controller object everytime, we make a http.post and it worked for me.
See if it works for you.
loading = this.loadingCtrl.create({
content: 'Loading'
});
init(){
this.loading = this.loadingCtrl.create({
content: 'Loading'
});
}

And inside your http call, do this!

doHttpPost (){
this.init();
this.loading.present();

this.http.post(this.loginUrl, JSON.stringify(requestBody), {headers: headers})
.toPromise()
.then(response => {
this.auth.authLogin(type, userInfo.usuario, response.json().token);
})
.catch(response => {
this.loading.dismiss();
});
}

Cheers!

@patrickmar
Copy link

patrickmar commented Mar 9, 2017

also experiencing same issue in ionic 2

@lucaspalencia
Copy link

@malick7

I was creating loadingController with a variable in the begin of my service and after in my method executing present() and dismiss().

Now i add the .create before the present() into my method and works well. Thank you!

@charIeszhao
Copy link

@malick7 Thank you! I have the same issue and now it works.

Hope the ionic team can fix this trivial defect as it's really not a good programming practice to initialize a new instance before calling present() method.

@shogunfighter
Copy link

I think you need to kill the instance of the loading class before reusing it again. That's why it's throwing errors.

Here, you can plug this provider/service if you want. I just edited this...


/**
 * Usage:
 *  
 *  //create loading service instance
 *  private loadingSvc:LoadingService;
 *  
 *  //this is how you show the loading instance
 *  loadingSvc.show("someRandomNameOfTheLoading","Message in the Loading instance");
 *  
 *  
 *  setTimeout(
 *  () => {
 *  
 *      //this is an example of how you kill the loading instance
 *      loadingSvc.hide("someRandomNameOfTheLoading");
 *  },
 *  2000
 *  )
 */

import {Injectable} from '@angular/core';
import {LoadingController, Loading} from 'ionic-angular';

@Injectable()
export class LoadingService {

    private loaderList:Array<Loading> = [];

    constructor(private loadingCtrl:LoadingController) {
        console.log('Hello LoadingService Provider');
    }

    /**
     * Creates a loading instance and present it
     * @param id
     * @param msg
     */
    public show(id, msg = 'Please wait...') {
        if(!this.loaderList[id]) this.loaderList[id] = this.loadingCtrl.create({
            content: msg
        });

        this.loaderList[id].present();
    }

    /**
     * Hide and then automatically remove the loading instance
     * @param id
     * @returns {Promise<any>}
     */
    public hide(id) {
        let prom = this.loaderList[id].dismiss();
            prom.then(
                ()=> { this.remove(id); }
            );

        return prom;
    }

    /**
     * Call `remove` to manually remove the loading instance
     * @param id
     */

    //normally you don't manually use this method, better use the method -> hide()
    public remove(id) {
        delete this.loaderList[id];
        console.log("this.loaderList:",this.loaderList);
    }

}

I have been using this loading PROVIDER, just modify it to your specifications if you like...

@FernandoX7
Copy link

Still happening on latest version

@YannKauderer
Copy link

Hey guys this issue is still happening on latest version when calling this.loading.show() for me :/ any workarounds or solutions found ?

@ghost
Copy link

ghost commented May 4, 2017 via email

@ionitron-bot
Copy link

ionitron-bot bot commented Sep 3, 2018

Thanks for the issue! This issue is being locked to prevent comments that are not relevant to the original issue. If this is still an issue with the latest version of Ionic, please create a new issue and ensure the template is fully filled out.

@ionitron-bot ionitron-bot bot locked and limited conversation to collaborators Sep 3, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests