Navigating to a new state using Ionic can be done with the $state.go method within

I am experiencing an issue with Ionic routing after receiving a Push Notification. The notification contains a custom key, for example 'myKey'. When the user clicks on the notification message, it should open the application and the callback function must navigate to a specific page in the app. See below:

var notificationOpenedCallback = function(jsonData) {
  if (jsonData.additionalData) {
    if (jsonData.additionalData.myKey)
      location.href = jsonData.additionalData.myKey;
  }
}

In my Ionic application, I am using $stateProvider. When a notification is received, I want to navigate to the following state:

  .state('app.post', {
    url: "/posts/:postId",
    views: {
      'menuContent': {
        templateUrl: "templates/post.html",
        controller: 'PostCtrl'
      }
    }
  })

I have attempted the following code, where 'myKey' corresponds to the postID:

var notificationOpenedCallback = function(jsonData) {
  if (jsonData.additionalData) {
    if (jsonData.additionalData.myKey)
      $state.go('app.post', {'postId': + jsonData.additionalData.myKey});
  }
}

However, this is not working as expected. Here is the complete code snippet:

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {

 var notificationOpenedCallback = function(jsonData) {
  if (jsonData.additionalData) {
    if (jsonData.additionalData.myappurl)
      $state.go('app.post', {'postId': + jsonData.additionalData.myKey});
  }
}

    window.plugins.OneSignal.init("###############",
                                   {googleProjectNumber: "###########"},
                                   notificationOpenedCallback); 



    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }   
  });
})

Answer №1

To improve your code, make sure to include the $state parameter in your run block:

.run(function($ionicPlatform, $state) {
  $ionicPlatform.ready(function() {
    var notificationOpenedCallback = function(jsonData) {
      if (jsonData.additionalData) {
        if (jsonData.additionalData.myappurl)
          $state.go('app.post', {'postId': + jsonData.additionalData.myKey});
      }
    }
  })
  // don't forget about the continuation of your code
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The confusing case of jQuery's e.preventDefault: Unable to submit form despite preventing default behavior

Objective: Prevent the 'submit' button from functioning, validate fields, generate popover alerts for results, and submit form upon closing of popover. To achieve this, I have set up a hidden popover div. When the submit button is clicked, I uti ...

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Execute jquery commands after the function has finished

I am trying to implement the code below: $(":file").change(function () { if (this.files && this.files[0]) { console.log(this.files[0]); var reader = new FileReader(); ...

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...

The Angular directive is functional only for a single use

I am facing an issue with my Angular directive that only renders once. Subsequent attempts to call the template are unsuccessful. Here is the HTML snippet: <div ng-app="myApp"> A. <ui-foo value="1" /> B. <ui-foo value="2" /> ...

Node seems to be having trouble with exporting and requiring, as it claims the class is not defined

Within my codebase, I have created three essential classes: TypeChecker: require('./type_error_checker/TypeErrorChecker'); require('./transpiler/Transpiler'); class TypeChecker { constructor() { console.log("TypeChecker i ...

initiating a submission upon the occurrence of an onchange event on an input field of type "file"

I have encountered an issue while trying to submit a form using the onchange event of an input element with type file. The problem is that it submits an empty form even when a file has been chosen. Here is the code snippet: var form = document.createElem ...

Is there a way to get rid of the tiny black line beside the Instagram icon?

Here is the display on my website This is the code that was used I am struggling to identify the source of the small black "-" line next to the Instagram icon logo. ...

Troubleshooting TypeScript Modules in Visual Studio 2015 Update 2: Fixing the 'require' Undefined Error

While working in Visual Studio 2015 Enterprise with Update 2 installed, I decided to create a new TypeScript project called TypeScriptHTMLApp1 using the default template and settings. As part of this project, I added a new TypeScript file named log.ts and ...

Once the if condition is implemented, the functionality of the toggle button ceases to operate

Take a look at this demo link: http://jsbin.com/labuxuziraya/1/edit I encountered an issue where the button stops working after adding an if condition. I suspect there are some minor bugs in the code, but my level of experience is not enough to pinpoint t ...

The iPad experiences issues with AJAX Calls timing out after 30 minutes

I'm currently working on developing a web application specifically designed for iPad usage (using saved bookmarks, viewport tags, etc). The app sends an AJAX request using jQuery every 2 minutes to a server without session cookies that may time out, a ...

Encountered an unexpected forward slash while trying to parse JSON using

When passing a file, why does the `parseJSON` function fail? The file is stored in variable a and then I attempt to parse it using `parseJSON`. var a = "/android/contents/img/uploads/img_2A0.png"; var result = jQuery.parseJSON(a); The error being displa ...

Looking to customize session data for my online game within the same interface

I have successfully coded a game called Ninja Gold using PHP with CodeIgniter. The game works by setting session variables (Gold and Activities) when the index page loads if they are not set already. Each location clicked adds a certain amount of gold to t ...

Proper method for validating Jwt

Below is the code I have composed: jwt.verify(token.split(':')[1], 'testTest') I am attempting to verify this code in order for it to return true and proceed. The jwt being mentioned here serves as an example payload. Any suggestions ...

Having trouble passing a token for authentication in Socket.IO v1.0.x?

I am currently following a tutorial on creating a token-based authentication system, which can be found here. I have implemented the following code: Code in app.html: var socket = io('', { query: "token=i271az2Z0PMjhd6w0rX019g0iS7c2q4R" }); ...

Steps for changing an array of objects from a string into a regular array of objects

I am facing an issue where I have an array of objects in string format that I need to convert into a normal array of objects. I tried using the JSON.parse() method for conversion, but when attempting to access values like: this.contact_data[0].data.value, ...

When an element in vue.js is selected using focus, it does not trigger re

One of my tasks involves tracking the last selected input in order to append a specific string or variable to it later on. created: function () { document.addEventListener('focusin', this.focusChanged); } focusChanged(event) { if (event ...

Discover content within nested arrays - angularJS

I have a function written in angularJS that utilizes find to verify the presence of an item in an array; function checkCartItem(item) { return $scope.cart[0].cart_items.find(function(itm) { return itm.item_id === item.item_id }); } The fu ...

Obtain the RadNumericTextBox value using JavaScript or jQuery in an ASP.NET environment

In my ASP.Net Web Page, I have a RadNumericTextBox within a DetailsView. I am attempting to access this element in JavaScript using jQuery. Despite successfully obtaining the RadNumericTextBox as a variable in JavaScript and verifying that it contains all ...

Improving the Performance of DisplayField Binding in ExtJS 5

When I trigger a window to create a new item, there is a noticeable lag when passing in the record for the bound fields. The record is essentially a blank one with default values provided by the framework. In this demo, there are 3 buttons: The first but ...