1
@Injectable() export class HomeService {   
    private _tUrl = 'this should be on desktop'; 
    private _tUrl = 'this should be on mobile'; 
}

This is for the API call. I only want to use one depend on device size.

Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73

2 Answers2

1

Assuming the following logic:

@Injectable() export class HomeService {   
    ...

   fetchFromBackEnd():Observable<Foo>{
      // somehow get the current endpoint
      // and call a method from angular´s HttpClient
      // with the endpoint
   }
}

Considering this scenario, you have 2 pathways that lead to a possible solution:

  • Reactive (async)
  • Non reactive (sync)

The first one would look more or less like this:

import {Observable} from 'rxjs/Observable'
import {switchMap, take}from 'rxjs/operators';

@Injectable() export class HomeService {   
   url$: Observable<string>;

   constructor(){
     this.url$ = this.createUrlStream();
   }

   fetchFromBackEnd():Observable<Foo>{
      const fetch: string => Observable<Foo> = (url) => this.http.get<Foo>(url);
      return this.url$.pipe(take(1),switchMap(url => fetch(url)); 
   }

   private createUrlStream():Observable<string>{
      // logic to map media query changes to a URL
   }
}

The non reactive approach would look like:

@Injectable() export class HomeService {   
   get url(): string {
     // logic to synchronously match the current media breakpoints
     // to a URL
   }

   fetchFromBackEnd():Observable<Foo>{
      return this.http<Foo>(this.url);
   }
}

In order to not reinvent the wheel or directly deal with the window object or other implementation details, I would suggest you to introduce another layer of abstraction by using the LayoutModule of the angular material CDK lib.

By using the BreakpointObserver provided by the lib, the 2nd implementation would look like this:

@Injectable() export class HomeService {   
   get url(): string {
     return this.isMobile ? "mobileurl" : "desktopurl";
   }

   private get isMobile():boolean {
      // example
      return this.bpObserver.isMatched('(max-width: 599px)')
   }

   constructor(private bpObserver: BreakPointObserver){

   }

   fetchFromBackEnd():Observable<Foo>{
      return this.http<Foo>(this.url);
   }
}
Jota.Toledo
  • 27,293
  • 11
  • 59
  • 73
0

You can simply check using window.matchmedia to check viewport width of the device and then call API depend on device size. like this -

@Injectable() export class HomeService {   
 constructor(){
   let mq = window.matchMedia("screen and (min-width:640px)")
   if (mq.matches) {
        this._tUrl = 'this should be on desktop'; 
   }
   else { this._tUrl = 'this should be on mobile';  }
   ...........
 }
Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215