@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.
@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.
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:
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);
}
}
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'; }
...........
}