Promise returns undefined value inside ngOnInit in Angular 8 ionic 4

error typeerror cannot read property 'subscribe' of undefined angular 8
how to get value outside typescript subscribe function
return value from subscribe angular 6
angular subscribe undefined
angular 6 http post example
angular 8 http
http and observables angular 8
angular http pipe map

In my Ionic 4 angular 8 application I am using chrome extension to return tab URL. I am getting the tab URL value in function defined in service file but when invoked the service inside ngOnInit() I am getting undefined. Please help me to resolve this.

I want the URL value to be displayed in ngOnInit()

Inside service file

async chromeCall() {
    try {          
      const results = await chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { from: 'popup', subject: 'DOMInfo' }, (response) => {
          console.info("Tab ID:", tabs[0].id);
          this.CurrentPgUrl = response.webPgURL;
          console.log(this.CurrentPgUrl);//geting value here
          return this.CurrentPgUrl;
        });
      });
    }
    catch (err) {
      console.log(err);
      console.log("comes to error ");          
    }
  }

Inside ngOnit()

 ngOnInit(){
    this.apiService.chromeCall()
    .then(result => {
      this.url=result;
      console.log(this.url)//value undefined
 )};

chromeCall must return a promise - or anything, really, as it is written it's returning undefined. chrome.tabs.query is build with the callback recipe, not the promise recipe, so awaiting it won't do anything worthy of notice.

It should go something like this:

chromeCall() {
    return new Promise(
        (resolve, reject) => chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
// dive into the callback hell here, and on the final line...
            resolve(this.CurrentPgUrl);
        }
// and the appropriate number of closing `}`s

Alternatively, you might use a library that promisifies those methods. This one, for example, looks like it would do the job: https://www.npmjs.com/package/chrome-extension-async

Cannot assess the http post response data from , I am using a http request to get a url from a server and it returns to a variable i cannot access the variable data from other method. this is my code public urlcheck… go past your subscribe and simply console log out a promise object that Component, OnInit } from '@angular/core'; import { Subject } from  I'd like to use Promise with OnInit. Similar implementation already exists on routerOnActivate. OnActivate - ts. If routerOnActivate returns a promise, the route change will wait until the promise settles to instantiate and activate child components. I want the component to wait its instantiation until the promise returned by ngOnInit resolved.

you can try like this, Here we are using a promise so after getting the expected result from chrome tabs we are resolving the promise so you will not get undefined. I hope it helps you out.

async chromeCall() {
    try {

      const results = await chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
   return new Promise(resolve => {
          chrome.tabs.sendMessage(tabs[0].id, { from: 'popup', subject: 'DOMInfo' }, 
          (response) => {
             console.info("Tab ID:", tabs[0].id);
             this.CurrentPgUrl = response.webPgURL;
             console.log(this.CurrentPgUrl);//geting value here
             resolve (this.CurrentPgUrl);
        });
      });
   });     
    }
    catch (err) {
      console.log(err);
      console.log("comes to error ");

    }
  }

ngOnInit

 ngOnInit(){
    this.apiService.chromeCall()
    .then(result =>{
    this.url=result;
    console.log(this.url)//value undefined
    )};

Properties value is undefined in method which returns promise , Properties value is undefined in method which returns promise · ionic not be “​undefined”, they should contain there real values inside this object. AaronSterling July 14, 2017, 2:17am #4 import { Injectable } from '@angular/​core'; import { Http } from '@angular/http'; import david95thinkcode July 18, 2017, 8:22pm #11. In this Angular 8/9/10 Promise tutorial, we are going to learn how to manage asynchronous HTTP response with JavaScript Promise objects. Get the full code of this tutorial on the following GitHub repo: Git Repo Introduction to JavaScript Promise Promises in ECMAScript are very much identical to the promises we make in our daily life. […]

option 1 : You can put async await concept for ngOnInit method which is like this,

async ngOnInit(){
    let serviceResponse = await this.apiService.chromeCall();
     if(serviceResponse){
       this.url=result;
     }
 }

option 2: You can add if condition in side then call back method, which is like this,

ngOnInit(){
    console.log('Loading start')
    this.apiService.chromeCall()
    .then(result =>{
        if(result){
            this.url=result;
            console.log('Loading ends')
            console.log(this.url)
            return
        }
        console.log('Loading ends')
    ).catch(err) => {
        console.log('Loading ends', err);
    }
};

Get a value from the localstorage and store it in a variable, 4. __proto__: Object. How to recover __zone_symbol_value ? I tried doing a console.log (latVal) but the result is undefined. I'm cascading the promises, so storage.get() will only run after storage.set() and this import {Component, OnInit​} from '@angular/core'; import {Geolocation, Geoposition} from  Ionic is the app platform for web developers. Build amazing mobile, web, and desktop apps all with one shared code base and open web standards <!--t.4.5.4.0-->Ionic Docs

Cannot read property 'subscribe' of undefined [SOLVED], getUsuarioInventiva(control.value).subscribe(data => { if (data Async validators must return a future (Promise or Observable). Following that rule will save you from 80% of common async bugs, I had a method that subscribes to an observable, calling that method within ngOnInit, raised this error. The Promise.resolve() method returns a Promise object that is resolved with a given value. If the value is a promise, that promise is returned; if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like

[SOLVED] Ionic 3 and Angular 4, Runtime Error Uncaught (in promise): TypeError: Cannot read property 'title' of undefined import { Component } from '@angular/core'; import { Platform } from navCtrl: NavController, private vinceSerivce:VinceService) { } ngOnInit(){ this. So, at the time you are trying to access these values they are not yet defined. ngOnInit and constructor methods in Angular might be confusing to you,if you are new to Angular.In this tutorial, we will cover the differences between ngOnInit & constructor. Table of Contents What is a Constructor?

Angular 2 Service Observable returns undefined - angular - html, Angular 2 Service Observable returns undefined - angular. Component: import { Component, OnInit } from '#angular/core'; import { Album } and have concluded that for some reason the service returns before the Promise 8 answers Good evening to all. I'm new to Angular 4, I'm trying to make simple app with an api. Promises are a far cleaner solution to writing asynchronous code than callbacks. The resulting code that’s created is easier to read and is often written the order the application will execute. So it can be easier to trace through code in your head. With the catch handler it also gives us a singl…

Comments
  • Do you mean this.CurrentPgUrl is undefined when you log it?
  • Instead of using function(tabs) {...}, I'd recommend using (tabs) => {...}. This is because function creates a new scope, so this won't refer to the same thing anymore.
  • I'm not sure that's the issue you have, but it might be
  • Yes, I need this.currentPgurl in ngOnit().But now I am getting undefined
  • Did you try using the fat arrow (=>) instead of function?
  • Getting the value as expected. Thanks
  • Still I am getting undefined in ngOnInit().
  • @SRI did you try to write await before the function(tabs) { ... } ?