#How do I access a component's function in service

1 messages · Page 1 of 1 (latest)

wheat tangle
#

You shouldnt do that, instead you should have a way to notify the component from in the service, using an observable.

#

So that in your component, you can do

this.connectionService.someObservableUsedToNotify.subscribe(() => {
  // call any method from the component here
})
#

I can try and help u, if you elaborate where in there service you want to communicate back to the component

reef raven
#

in the app.component.ts file, I want access the displayInternetPopUp method which is in the service

isThereInternet() {
    return this.connectionService.status === true
      ? this.displayInternetPopUp()
      : false;
  }
#

For that to happen, I have to access the ngOnInit in the component

#

@wheat tangle

wheat tangle
#

I dont think I understand

For that to happen, I have to access the ngOnInit in the component

#

If u need to access a service method from a component, u just call the method.

reef raven
#

Yeah but first I need to access the ngOnInit of the component right

#

for the displayInternetPopUp function to work

wheat tangle
#

I am not sure I understand what u mean.

#

You should never call a component's method from inside a service.

reef raven
#

So you are saying that we cannot access a component's method inside a service right?

wheat tangle
#

Yes.

#

And I am also saying you shouldnt need to.

#

If you explain what you want to achieve, and not how you think you need to achieve it, we can try and help.

reef raven
#

I want to make use of service to check whether Internet is there or not

#

And it will bring up a popup component

#

which is serverResponseDisplayService

#

and in that there is button to try again

#

when a user clicks that button, the page should be refreshed

#
this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp
      .pipe(take(1))
      .subscribe(data => {
        if (data === 'retry') {
          this.ngOnInit();
        }
      });
  }
wheat tangle
#

And which of that requires to call ngOnInit?

reef raven
#

yes

wheat tangle
#

That wasn't a yes/no question tho 😄

#

So what you can do is:

#
export class InternetCheckService {
  status: boolean = false;
  isConnected: boolean = true;

  reloadSubject = new Subject();
  reload$ = reloadSubject.asObservable();

  displayInternetPopUp() {
    this.serverResponseDisplayService.errorMessageToShow({
      title: 'No internet connection.',
      buttonText: 'Close',
      message: 'Please try again later or try refreshing the page.',
    });

    this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp
      .pipe(take(1))
      .subscribe(data => {
        if (data === 'retry') {
          this.reloadSubject.next();
        }
      });
  }
}
#

And in your component, use:

export class AppComponent {
 constructor(private readonly connectionService: InternetCheckService){}
 ngOnInit() {
    this.loadData();
    this.connectionService.reload$.subscribe(() => {
      this.loadData();
    });
  }

  loadData() {
    this.registerLocale();
    this.subscribeToTitleService();
    this.documentOrientationListener();
  }
}
#

However, you shouldnt need to call all those methods again.

#

But anyway, this should achieve what you are asking for.

#

Be sure to unsubscribe any previous subscription when you resubscribe like that.

reef raven
#

How to unsubscribe it?

wheat tangle
#

calling unsubscribe.

reef raven
#

oh okay

#

An error is occuring in this.reloadSubject.next();
Subject.d.ts(32, 10): An argument for 'value' was not provided.

wheat tangle
#

new Subject<void>

reef raven
#

When I do that , i get this error
error TS2532: Object is possibly 'undefined'.

wheat tangle
#

Where

reef raven
#

Error: Module parse failed: Unexpected token (35:56)
File was processed with these loaders:

  • ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
  • ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
  • ./node_modules/@ngtools/webpack/src/ivy/index.js
    You may need an additional loader to handle the result of these loaders.
    | constructor() {
    | this.isConnectedToInternet = true;
    this.reloadSubject = new rxjs_2.Subject < void  >

| reload$;
| }

#

@wheat tangle

wheat tangle
#

I cant see how that error relates to what we talked about.

reef raven
#

error TS2532: Object is possibly 'undefined'.

13 reloadSubject = new Subject<void>

#

It's on the edit you told me to do

#

new Subject<void>

wheat tangle
reef raven
#

reloadSubject

wheat tangle
#

Please share the code that introduces this

reef raven
#
import {Injectable} from '@angular/core';
import {ConnectionService} from 'ng-connection-service';
import {ServerResponseDisplayService} from '@components/ui/server-response-display/server-response-display-service/server-response-display.service';
import {take} from 'rxjs';
import {Subject} from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class InternetCheckService {
  isConnectedToInternet = true;

  reloadSubject = new Subject<void>
  reload$ = this.reloadSubject.asObservable();

  constructor(
    private connectionService: ConnectionService,
    private serverResponseDisplayService: ServerResponseDisplayService
  ) {
    this.connectionService.monitor().subscribe(isConnected => {
      this.isConnectedToInternet = isConnected.hasInternetAccess;
      if (!this.isConnectedToInternet) {
        this.displayNoInternetMessage();
      }
    });
  }
  displayNoInternetMessage() {
    this.serverResponseDisplayService.errorMessageToShow({
      title: 'No internet connection.',
      buttonText: 'Close',
      message: 'Please try again later or try refreshing the page.',
    });

    this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp
      .pipe(take(1))
      .subscribe(data => {
        if (data === 'retry') {
          this.reloadSubject.next();
        }
      });
  }
}
wheat tangle
#

And which line is giving that error ?

reef raven
#

this.reloadSubject.next();

wheat tangle
#

I dont see why that would give that error

reef raven
#

wait a min

#

Small edition in code

#

Now there are no erros in the code

#

But in terminal lots of errors are coming

#

Most of them are showing this error

#

error TS2532: Object is possibly 'undefined'.

13 reloadSubject = new Subject<void>

#

error TS2532: Object is possibly 'undefined'.

14 reload$ = this.reloadSubject.asObservable();

#

Object is possibly 'undefined'.

28 this.serverResponseDisplayService.errorMessageToShow({

#

Object is possibly 'undefined'.

34 this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp

#

error TS2532: Object is possibly 'undefined'.

38 this.reloadSubject.next();

#

Do you have any other solution to overcome this errors? @wheat tangle

wheat tangle
#

Did you try restarting the terminal ?

reef raven
#

let me try that

#

Yup I did that, still all of the errors are coming

#

Error: Module parse failed: Unexpected token (35:56)
File was processed with these loaders:

  • ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
  • ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
  • ./node_modules/@ngtools/webpack/src/ivy/index.js
    You may need an additional loader to handle the result of these loaders.
    | constructor() {
    | this.isConnectedToInternet = true;
    this.reloadSubject = new rxjs_2.Subject < void  >

| reload$;
| }

#

This is the first error which pops up

wheat tangle
#

As mentioned, I cant see how the changed we talked about can cause that.

reef raven
#

When I change reloadSubject = new Subject<void> to reloadSubject = new Subject(), all the errors go away

#
error TS2554: Expected 1 arguments, but got 0.

38           this.reloadSubject.next();
                                ~~~~~~

  node_modules/rxjs/dist/types/internal/Subject.d.ts:32:10
    32     next(value: T): void;
                ~~~~~~~~
    An argument for 'value' was not provided.
#

and only this error is shown

#

Any other way we can tackle this problem @wheat tangle

wheat tangle
#

I cant see how the change we talked about can cause that.

#

Based on what you shared, I cant be helpful.

reef raven
#

I found out the problem

#

We had to add new Subject<void>();

#

@wheat tangle

#

But when I click the try again button it does not load the ngOnInit

#

The popup is not getting loaded again

wheat tangle
reef raven
#

I did'nt put ()

#

Do you have any idea why ngOnInit is not loading when try button is clicked @wheat tangle

wheat tangle
#

Can you show your component

reef raven
#

app.component.html

<div class="app-container">
  <app-server-response-display></app-server-response-display>
  <router-outlet></router-outlet>
</div>
wheat tangle
#

I Mean the one about the oninit

reef raven
#
import {Component, HostListener} from '@angular/core';
import {ActivatedRoute, Data, NavigationEnd, Router} from '@angular/router';
import {Title} from '@angular/platform-browser';
import {filter} from 'rxjs/operators';
import {TitleService} from '@services/title/title.service';
import {registerLocaleData} from '@angular/common';
import localeDe from '@angular/common/locales/de';
import {InternetCheckService} from '@services/internet-check/internet-check.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'admin';

  initialHeight = 0;
  previousOrientation: any;
  currentOrientation: any;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private toolbarTitle: Title,
    private toolbarTitleService: TitleService,
    private readonly internetCheckService: InternetCheckService
  ) {}

  ngOnInit() {
    this.registerLocale();
    this.subscribeToTitleService();
    this.documentOrientationListener();
  }

  get isMobileDevice() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    );
  }

  registerLocale() {
    registerLocaleData(localeDe, 'de');
  }

  subscribeToTitleService() {
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(() => {
        const route = this.getChild(this.activatedRoute);
        route.data.subscribe((data: Data) => {
          this.toolbarTitle.setTitle(
            this.toolbarTitleService.getFormattedTitleName(data.title)
          );
        });
      });
  }
wheat tangle
#

Where is the part that subscribes on the observable?

reef raven
#

Oh I forgot to update that

#

Updating it now

reef raven
#

I'm still not able to load ngOnInit when I click the try again button

#

@wheat tangle

wheat tangle
#

I dont see it ?

reef raven
#

what are you not seeing?

#

try button? @wheat tangle

reef raven
#
import {Component, HostListener} from '@angular/core';
import {ActivatedRoute, Data, NavigationEnd, Router} from '@angular/router';
import {Title} from '@angular/platform-browser';
import {filter} from 'rxjs/operators';
import {TitleService} from '@services/title/title.service';
import {registerLocaleData} from '@angular/common';
import localeDe from '@angular/common/locales/de';
import {UtilsService} from '@services/utils/utils.service';
import {InternetCheckService} from '@services/internet-check/internet-check.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  title = 'admin';

  initialHeight = 0;
  previousOrientation: any;
  currentOrientation: any;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private utils: UtilsService,
    private toolbarTitle: Title,
    private toolbarTitleService: TitleService,
    private readonly internetCheckService: InternetCheckService
  ) {}

  ngOnInit() {
    this.loadData();
    this.internetCheckService.reload$.subscribe(() => {
      this.loadData();
    });
  }

  loadData() {
    this.registerLocale();
    this.subscribeToTitleService();
    this.documentOrientationListener();
  }

  registerLocale() {
    registerLocaleData(localeDe, 'de');
  }
#

This is the code now

wheat tangle
#

And what is not working ?

reef raven
#

when I click try again button in the popup, it should load ngOnInit right

wheat tangle
#

no

#

it calls loadData

reef raven
#

yeah loadData

#

it is not calling it

#

I added dummy text in loadData and console logged it

#

the text is not shown in console

wheat tangle
#

Okay, its hard to tell.

#

Would be useful if you can start reproducing this on stackblitz, that way we can help.

reef raven
#

ok let me try that

reef raven
#

Hey @wheat tangle , I copied all of the code required to run into stackblitz but the website is not loading. Could you check where I'm going wrong?

wheat tangle
#

It loads for me, but I only see the default content.

#

Did u save properly ?

reef raven
#

Could you turn off the wifi and see if the internet check works

#

I saved it, still no content is shown

wheat tangle
#

Not sure why it would show anything ...

#

You need to use the service.

reef raven
#

what service

wheat tangle
#

InternetCheck

reef raven
#

the service is used in the app.component.ts file

wheat tangle
#

Its not on the stackblitz I am looking at

#

Ah its now when I refresh

reef raven
#

yeah

wheat tangle
#

You didnt bootstrap it.

#

Look at main.ts

#

its using a different app component

reef raven
#

I redirected index.html, component loader to app-loader

#

which redirects to app.component.ts

wheat tangle
#

No idea what you are saying

#

but the stackblitz isnt bootstrapping your app component

#

please fix that

reef raven
#

How to fix that?

#

Im new to stackblitz

wheat tangle
#

This has nothing to do with stackblitz

#

open main.ts

reef raven
#

ok

wheat tangle
#

there is bootstrapApplication

#

it's using the App from inside main.ts. Not yours.

#

Fix that.

#
  • move your app component in the src folder
  • make app component standalone
  • import app component in main.ts
  • use it to pass to bootstrapApplication
  • remove App from main.ts
reef raven
#

I did it but still the app is not loading

#

Could you check on your end @wheat tangle

wheat tangle
#

You didnt do what I said above...

reef raven
#

I can't import and export appComponent in the same file

wheat tangle
#

No idea what you mean.

reef raven
#
import 'zone.js/dist/zone';
import { Component, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from 'src/app/app.component';

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule],
  template: `
    <h1>Hello from {{name}}!</h1>
    <a target="_blank" href="https://angular.io/start">
      Learn more about Angular 
    </a>
  `,
})

export class AppComponent{
  name = 'Angular';
}

bootstrapApplication(AppComponent);
#

When i do this in main.ts

#

Individual declarations in merged declaration 'AppComponent' must be all exported or all local.

#

i get this error

wheat tangle
#

You need to remove AppComponent from main

#

I told u to do that

reef raven
#

You told to remove App

wheat tangle
#

It was named App ye.

reef raven
#

yeah I replaced App with AppComponent

wheat tangle
#

I said remove, not replace.

reef raven
#

ok

#

so what about the parameter in bootstrap application

#

im confused 😅

wheat tangle
#

Here I fixed it.

#

But please learn how to use Angular.

reef raven
#

Still I'm getting no display

wheat tangle
#

What if u refresh ?

#

I also configured the application like this:

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(),
    {
      provide: ConnectionService,
      useValue: {
        monitor: () => of({ hasInternetAccess: false }),
      },
    },
  ],
});

#

so u do not need to disable wifi.

#

It runs as if there is no wifi.

#

But I cant see anything in that code that would show a popup or so.

reef raven
wheat tangle
#

I have no idea what your code should do.

reef raven
wheat tangle
#

But the internet check works.

wheat tangle
reef raven
#
displayNoInternetMessage() {
    this.serverResponseDisplayService.errorMessageToShow({
      title: 'No internet connection.',
      buttonText: 'Close',
      message: 'Please try again later or try refreshing the page.',
    });

    this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp
      .pipe(take(1))
      .subscribe((data) => {
        if (data === 'retry') {
          this.reloadSubject.next();
        }
      });
  }
wheat tangle
#

That doesnt display anything

reef raven
#

serverResponseDisplayService is used for displaying the popup

wheat tangle
#

Its not.

reef raven
wheat tangle
#

All it does is emit events.

#

It doesnt show any popup,.

reef raven
wheat tangle
#

There is nothing that shows a popup.

#

Its not that the popup isnt showing.

#

There is no code that shows a popup.

#

What code should show a popup?

reef raven
#

see server-response-display.component.html

#

that is the popup code

#

the app,component.ts file automatically calles the InternetCheck service

#

Like that the pop up is shown

wheat tangle
#

Sorry I do not understand how a popup should be shown.

#

Where is server response display rendered ?

reef raven
#

go to app,component.ts

#

do you see constructor(private readonly internetCheckService: InternetCheckService) {}

#

from there the service is called

wheat tangle
#

Where is server response display rendered ?

#

Forget about the service

reef raven
#

in app.component.html

wheat tangle
#

its not

#
<div class="app-container">
  <h1>Internet Check</h1>
</div>

#

thats the html I see.

reef raven
#

yeah it activates in app.,component.ts and render in app.component.html

wheat tangle
#

The code for showing a popup is not used.

reef raven
#

if there is no internet in app.component.html, it will display the popup

wheat tangle
#

No.

reef raven
#

but it works for me

wheat tangle
#

It does not work in stackblitz.

reef raven
#

locally

wheat tangle
#

Because of what I said.

#

The code that shows the popup is never called, because its not part of app component.

#

So if u ask why a popup isnt shown, it's because you never try and show one on the stackblitz.

reef raven
#

but why is it working locally?

#

im using the same code as stackblitz locally, but the popup is coming then

wheat tangle
#

Did u save ?

#

As the component u mention is not inside app.component.

reef raven
#

yeah i saved

wheat tangle
#

What sthe link ?

wheat tangle
#

That is all i see.

#

Click fork and save please.

reef raven
#

yeah that is what i see too

wheat tangle
#

So now I am lost.

#

How would u expect a popup to be shown?

reef raven
#

when it is running the InternetCheck service inside app.component.ts

wheat tangle
#

There is no code in app.component.ts to display a popup.

reef raven
#

without any code , the app is displaying the popup bro

wheat tangle
#

Clearly it's not ?

#

But if its display the popup, I guess there is no problem.

reef raven
#

@wheat tangle I have updated the code could you check now

wheat tangle
#

link?

reef raven
wheat tangle
reef raven
#

I have imported

import { ServerResponseDisplayComponent } from 'src/ui/server-response-display/server-response-display.component';
#

Could you check now

wheat tangle
#

Does it work for you on stackblitz ?

reef raven
#

I told you there is no output coming for me in stackblitz

#

I dont know why

#

I tried refreshing too

wheat tangle
#

Maybe u should solve that.

#

Its full of errors

#

'app-general-dialogue' is not a known element:

#

Ensure the stackblitz is running and I am happy to help you. But this is not a very useful way to use my time.

reef raven
#

Hey, my stackblitz is running now

#

But im not able to solve thsis error

'app-server-response-display' is not a known element:
wheat tangle
#

Yeah u need to fix that.

reef raven
#

I tried importing the component to app.component.ts file

wheat tangle
#

Whats the link ?

reef raven
wheat tangle
#

Where did u try and import the component ?

reef raven
#

the route to ServerResponseDisplayComponent is correct but still module not found error is coming

#

to app.component.ts

wheat tangle
#

That's not what you should do.

reef raven
#

Then?

wheat tangle
#

I'm sorry, it does look like you should take a step back and try and understand what we are doing.

#

In order to use a component, u dont just import {SomeComponent} from 'path'.

reef raven
#

I only declared it in the module

wheat tangle
#

Where are you importing that module?

reef raven
#

in app.module.ts

wheat tangle
#

And where is ServerModule?

reef raven
#

in server-response-display folder

wheat tangle
reef raven
#

Please refresh and check?

wheat tangle
#

Ah I see it now.

reef raven
#

Still why is it showing that error

wheat tangle
#

Your code is full of errors.

reef raven
#

where are these errors shown?

#

Im only seeing this

#

can i give you git repo?

#

@wheat tangle

wheat tangle
#

'app-general-dialogue' is not a known element:

#

I recommend you to take a step back and familiarize with Angular. I had to fix a lot of things to get to that error.

reef raven
#

could you share the updated link of stackblitz

wheat tangle
#

plz work from that version and fix the errors.

reef raven
#

okay

reef raven
#

I'm pointing to the correct file but still its saying module not found

#

import { GeneralDialogueModule } from 'src/ui/general-dialogue/general-dialogue.module';
Cannot find module 'src/ui/general-dialogue/general-dialogue.module' or its corresponding type declarations.

#

@wheat tangle

wheat tangle
#

I would advise you to take a step back and understand what's happening. I cant keep fixing all these copy paste issues.

#

Also use relative paths

#

Look at other import paths i added.

reef raven
#

I don't know what I'm doing wrong. I'm really confused why the path is giving me an error. @wheat tangle

wheat tangle
#

Use a relative path

reef raven
#
import { GeneralDialogueModule } from '../ui/general-dialogue/general-dialogue.module';
#

like this right?

wheat tangle
#

../..

#

Then u get

#

The class 'GeneralDialogueModule' is listed in the declarations of the NgModule 'ServerModule', but is not a directive, a component, or a pipe. Either remove it from the NgModule's declarations, or add an appropriate Angular decorator.

#

Which is all copy paste errors that I cant keep fixing for you, sorry.

#

Same with the relative paths.

#

Ping me when the SB works, and I am happy to look at it.

reef raven
#

Here is the internet check popup which comes when the internet is not there. When I click the try again button, it should call the internet check function again

#

@wheat tangle

wheat tangle
#

Where can I find the code that reacts to clicking retry @reef raven ?

reef raven
#

Its on services -> internet-check.service.ts. It's this line

this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp
      .pipe(take(1))
      .subscribe((data) => {
        if (data === 'retry') {
          // call internet function again to check if internet connection is there or not
        }
      });
#

@wheat tangle

wheat tangle
#

And what component do u want to rexecute ?

#

I mean, based on the comment you want to call a method inside the same service

#

which isnt what you initially mentioned.

#

Do u want to keep showing a retry popup until there is internet?

wheat tangle
#

That is nowhere close to what you have been asking for days.

reef raven
#

I was mentioning that issue only

wheat tangle
#

Look at the threads title ... "How to access a components function in service".

reef raven
#

Actually I wanted to access ngOnInit

#

of app.component.ts

#

but then got to know that I want to access the constructor

wheat tangle
#

@reef raven Im not even getting a popup on your repo?

#

Anyway, this works for me:

#
export class InternetCheckService {
  isConnectedToInternet = true;

  constructor(
    private connectionService: ConnectionService,
    private serverResponseDisplayService: ServerResponseDisplayService
  ) {
    this.connectionService.monitor().pipe(
      delay(500),
      take(1),
      mergeMap((connectionState) =>
        connectionState.hasInternetAccess
          ? of(false)
          : this.displayNoInternetMessage()
      ),
      filter(retry => !!retry),
      repeat()
    ).subscribe(console.log);
  }
  displayNoInternetMessage() {
    this.serverResponseDisplayService.errorMessageToShow({
      title: 'No internet connection.',
      buttonText: 'Close',
      message: 'Please try again later or try refreshing the page.',
    });
    return this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp.pipe(
      take(1),
      map((data) => data === 'retry')
    );
  }
}
#

You do want to get rid of the delay.

reef raven
#

I'm getting the popup

wheat tangle
#

Ah yeah, makes sense.

reef raven
#

Im getting lots of error

#

When i changed the code

wheat tangle
#

Let me try something else first.

reef raven
#

Okay

#

Are you getting the popup?

wheat tangle
#

Yeah, and clicking retry shows it again.

#

But I will need to change a few things.

reef raven
#

Okay

wheat tangle
#

Whats the point of the retry function tho?

#

As monitor will keep monitoring untill internet is back ?

#

there is no real retry.

#

I think it would be better to show a popup saying NO INTERNET

#

without retry

#

and wait untill monitor shows u have internet again

#

and close it

reef raven
#

No i have to keep the try again button on the project

#

Can we make the try again functionality work?

wheat tangle
#

So when u show a popup, you want to wait for manual retry, even if internet is back sooner?

reef raven
#

Yeah

wheat tangle
#

Uff, okay. That might be complicated.

reef raven
#

If internet is back sooner, then the popup could be closed

wheat tangle
#

I dont think the library u use is designed for what you try to do.

#

it's used to monitor for internet connection, not for manual checking if there is internet connection.

reef raven
#

I dont want to manual check

#

I just want to check whether there is internet is there or not, while clicking on retry button

#

If there is not the popup should again appear

#

or else it should not appear

wheat tangle
#

clickin retry is a manual check.

#

which the library does not support.

#

The librarry checks automatically every 3 seconds.

reef raven
#

You said clicking retry shows it again, how did you do that?

#

@wheat tangle ?

wheat tangle
#

Basically using repeat()

reef raven
wheat tangle
#

It's a good start, but not the final solution as I believe the library you have doesnt realy do what you want to do.

reef raven
#

I tried that code but when the wifi is turned on, still the popup is getting displayed over and over again

#

@wheat tangle Any idea why?

wheat tangle
#

Well the library does not allow to do what you want

#

It takes 3 seconds before it picks up the connection

reef raven
#

Thats okay for me

#

I just want to close or not show the popup when there is internet @wheat tangle

wheat tangle
#

Do you already have the ability to close the popup?

reef raven
#

No when I click the close button, it reloads the popup

wheat tangle
#

Track the open popup, and close it when monitor emits true

reef raven
#

code example ?

#

How to know if monitor emits true and how to track the open popup

reef raven
wheat tangle
#

Did you track the popup ?

#

You cant close it if you don't track it.

reef raven
#

No I wasnt able to track it

wheat tangle
#

What have you tried ?

reef raven
#

When the internet is turned on, I tried to make the popup disappear. But could not do that

#

Still the popup is coming again and again

#

Are you able to track the popup @wheat tangle

wheat tangle
#

What library do u use to open the popup

reef raven
#

It uses the server error display service that opens the popup

wheat tangle
#

Try using an existing solution, it allows to close popups most of the time.

reef raven
#

What type of solution are you talking about

wheat tangle
reef raven
#

@wheat tangle I was able to close the popup. But when I close it, it does not reappear when internet it turned off

#

I used this on the server error display component

(click)="modalRef?.hide()">
wheat tangle
#

Honestly, I have no idea what you are trying anymore. i thought u wanted to closwe it when internet is back, not when u click somewhere.

reef raven
#

Yeah that works

#

but when i turn the wifi off again

#

the popup is not showing

wheat tangle
#

Yeah no idea man. That used to work before, so I have no idea what changed.

#

But as much as I want to help u, I think its better to not ping me 50 times per day

#

Update your github project, share it and be very clear in what you want.

#

There are alot of people thet can help you, not just me.

reef raven
#

Apparently the connection state's hasInternetAccess was not working properly. When I changed it to hasNetworkConnection, everything works fine. Thanks so much for patiently making me understand where I'm going wrong and rectifying my errors. @wheat tangle

reef raven
#

Hey @wheat tangle, I wanted to automatically close the popup when there is internet. So I modified your code like this, but it is giving me this error - Type '(() => void) | Observable<boolean>' is not assignable to type 'ObservableInput<any>'. Here is the modified code. Any idea why I'm not able to call that function?

import {Injectable} from '@angular/core';
import {ConnectionService} from 'ng-connection-service';
import {ModalPopupService} from '../../components/ui/modal-popup/service/modal-popup.service';
import {ServerResponseDisplayService} from '@components/ui/server-response-display/server-response-display-service/server-response-display.service';
import {take, delay, of} from 'rxjs';
import {mergeMap, repeat, map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class NetworkCheckService {
  isConnectedToInternet = true;

  constructor(
    private connectionService: ConnectionService,
    private serverResponseDisplayService: ServerResponseDisplayService,
    private modalPopup: ModalPopupService
  ) {
    this.connectionService
      .monitor()
      .pipe(
        delay(500),
        take(1),
        mergeMap(connectionState =>
          connectionState.hasNetworkConnection
            ? this.popUpCloseHandler
            : this.displayNoInternetMessage()
        ),
        repeat()
      )
      .subscribe();
  }
  displayNoInternetMessage() {
    this.serverResponseDisplayService.errorMessageToShow({
      title: 'No internet connection.',
      buttonText: 'Close',
      message: 'Please try again later or try refreshing the page.',
    });
    return this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp.pipe(
      take(1),
      map(data => data === 'retry')
    );
  }
  popUpCloseHandler() {
    this.modalPopup.close('error-popup');
  }
}
wheat tangle
#

The issue is with popupCloseHandler inside mergeMap

#

You need to add ()

#

As well as return an observable

reef raven
#

I just want to close the popup

#

how do i return that as an observable

wheat tangle
#

You can use tap if u don't want to return an observable.

#

But if u use mergeMap u need to return an observable.

reef raven
#

is there any way other than mergeMap to use the ternary operation

wheat tangle
#

The second part returns an observable

#

So yeah mixing those two in a single ternary is gonna be a bit weird.

reef raven
#

Oh okay

#

So how can I return this as a observable

popUpCloseHandler() {
    this.modalPopup.close('error-popup');
  }
reef raven
#

I figured out a way @wheat tangle . But still, the popup is not getting automatically closed when I turn on the internet.

import {Injectable} from '@angular/core';
import {ConnectionService} from 'ng-connection-service';
import {ModalPopupService} from '../../components/ui/modal-popup/service/modal-popup.service';
import {ServerResponseDisplayService} from '@components/ui/server-response-display/server-response-display-service/server-response-display.service';
import {take, delay, of} from 'rxjs';
import {mergeMap, repeat, map} from 'rxjs/operators';
import {Observable} from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class NetworkCheckService {
  isConnectedToInternet = true;

  constructor(
    private connectionService: ConnectionService,
    private serverResponseDisplayService: ServerResponseDisplayService,
    private modalPopup: ModalPopupService
  ) {
    this.connectionService
      .monitor()
      .pipe(
        delay(500),
        take(1),
        mergeMap(connectionState =>
          connectionState.hasNetworkConnection
            ? this.popUpCloseHandler()
            : this.displayNoInternetMessage()
        ),
        repeat()
      )
      .subscribe();
  }
  displayNoInternetMessage() {
    this.serverResponseDisplayService.errorMessageToShow({
      title: 'No internet connection.',
      buttonText: 'Close',
      message: 'Please try again later or try refreshing the page.',
    });
    return this.serverResponseDisplayService.messageDisplaySubscribableFromPopUp.pipe(
      take(1),
      map(data => data === 'retry')
    );
  }
  popUpCloseHandler(): Observable<boolean> {
    return new Observable(observer => {
      this.serverResponseDisplayService.messageDisplayFromPopUp.next('custom');
      observer.next(true);
      observer.complete();
    });
  }
}
wheat tangle
#

Why would it get closed ?

#

U have a take(1)

reef raven
#

Okay, so what should I do? I'm confused

#

Should I remove take(1)

wheat tangle
#

Yeah I'd think so.

reef raven
#

Yeah I did that, still does not work. Any other way @wheat tangle

reef raven
#

Do you have any ideas @wheat tangle

#

Im out of new ideas

wheat tangle
#

I have no idea what doesnt work.

#

As mentioned before, I encourage you to use something that already exists to handle popups.

reef raven
#

Here is the console log

#

I found out something

#

When the internet is turned off

#

The internet check gives false and then never checks again

#

Until the close button is click

wheat tangle
reef raven
#

Yeah with the take(1)

wheat tangle
#

Sounds expected.

reef raven
#

I think it's because mergeMap checks the internet check only when connectionState hasNetworkConnection

wheat tangle
#

take 1 means ... only take 1.

reef raven
#

I tried again with deleting take(1)

#

Still in the console im getting like that