Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 2, 2022 10:16 am GMT

Msg: Unhandled Promise rejection: Cannot read properties of undefined (reading 'data') - Angular

My angular application has a class which detects network status:

@Injectable({  providedIn: 'root'})export class NetworkAutoSyncService {  protected isConnected = true;  constructor(    protected network: Network,    protected loadingController: LoadingController,    protected syncServices: SyncMasterService,    protected userParameterService: UserParametersService  ) {    this.networkSubscriber();  }  networkSubscriber() {    if (this.network.type == 'none') {      this.isConnected = false;    }    this.network.onDisconnect().subscribe(() => {      console.log('network was disconnected :-(');      this.isConnected = false;    });    this.network.onConnect().subscribe(async () => {      if (!this.isConnected) {        this.isConnected = true;        const loading = await this.loadingController.create({          message: 'Network Connected - Sync In Progress',        });        await loading.present();        await this.syncServices.syncUserParams().then((res: any) => {          this.syncUserParameter(res.data.userParameters, res.data.flag);        });        await loading.dismiss();      }      console.log('network connected!');      setTimeout(() => {      }, 3000);    });  }  protected syncUserParameter(userParams, flag) {    console.log('sync user params');    if (flag == 'update') {      this.userParameterService.updateUser(userParams);    }  }}

this class is declared in the app.module as networkAutoSyncService

@NgModule({  declarations: [AppComponent],  entryComponents: [],  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, HttpClientModule, FormsModule],  providers: [SQLite, {    provide: RouteReuseStrategy,    useClass: IonicRouteStrategy  }, Network, DatetimeConversions    // , {    //   provide: ErrorHandler,    //   // Attach the Sentry ErrorHandler    //   useValue: SentryAngular.createErrorHandler(),    // },  ],  bootstrap: [AppComponent],})export class AppModule {  constructor(    protected userParamsService: UserParametersService,    protected syncServices: SyncMasterService,    public networkAutoSyncService: NetworkAutoSyncService  ) {  }}

Now when network is reconnected this code runs from above:

    await this.syncServices.syncUserParams().then((res: any) => {      this.syncUserParameter(res.data.userParameters, res.data.flag);    });

which calls syncUserParams() in this sync master services class:

@Injectable({  providedIn: 'root'})export class SyncMasterService {  protected endpoint;  constructor(    protected network: Network,    protected userParamsService: UserParametersService,    protected getUserCreds: GetUserCredsServiceService,  ) {    this.endpoint = environment.syncendpoint;  }  public async syncUserParams(): Promise<AxiosResponse<any> | void> {    const token: string = await this.getUserCreds.getStoredToken();    const userUUID: string = await this.getUserCreds.getStoredUuid();    try {      console.log('Here we break');      this.userParamsService.getUserParameters(userUUID).then(data => {        console.log(JSON.stringify(data));        axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';        axios.defaults.headers.post.Authorization = token;        const url = this.endpoint;        return axios.post(url, {          data        }).then((response) => {          if (response.data.status == 'success') {            return response;          }        });      });    } catch (e) {    }    return;  }}

As see the above the syncUserParams function is called which calls getUserParameters() in the below class. However error happenes after console.log('Here we break'); when we call getUserParameters with this error

 Unhandled Promise rejection: Cannot read properties of undefined (reading 'data')

function inside the dbservice class (We do not reach inside this function)

@Injectable({  providedIn: 'root'})export class UserParametersService {  readonly dbName: string = 'global.db';  readonly dbTable: string = 'userParametersTable';  protected dbInstance: SQLiteObject;  constructor(    protected platform: Platform,    protected sqlite: SQLite,    protected globalDbFunctions: GlobalDBFunctionsService,    protected syncServices: SyncMasterService  ) {    this.databaseConn();  }  /**   *   * @param uuid   */  public getUserParameters(uuid) {console.log('this does not output so this function does not get called properly');    return this.dbInstance.executeSql(`SELECT * from ${this.dbTable} where uuid = ?`, [uuid])      .then((res) => {        if (res.rows.length == 1) {          return res.rows.item(0);        }        return false;      }).catch(e => {        console.log(JSON.stringify(e));      });  }}

Wondering how I can solve this
Thanks

The full error:

    E/Capacitor/Console: File: http://localhost/polyfills.js - Line 1115 - Msg: Unhandled Promise rejection: Cannot read properties of undefined (reading 'data') ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read properties of undefined (reading 'data') TypeError: Cannot read properties of undefined (reading 'data')            at http://localhost/main.js:2495:48            at ZoneDelegate.invoke (http://localhost/polyfills.js:413:30)            at Zone.run (http://localhost/polyfills.js:173:47)            at http://localhost/polyfills.js:1331:38            at ZoneDelegate.invokeTask (http://localhost/polyfills.js:447:35)            at Zone.runTask (http://localhost/polyfills.js:218:51)            at drainMicroTaskQueue (http://localhost/polyfills.js:633:39)

Original Link: https://dev.to/flyingman/msg-unhandled-promise-rejection-cannot-read-properties-of-undefined-reading-data-angular-5gf2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To