Angular:根据媒体断点更改服务端点

时间:2018-05-17 10:15:30

标签: angular typescript media-queries

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

这是用于API调用的。我只想使用一个取决于设备大小。

2 个答案:

答案 0 :(得分:1)

假设以下逻辑:

@Injectable() export class HomeService {   
    ...

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

考虑到这种情况,您有2条途径可以找到可能的解决方案:

  • 反应(异步)
  • 非反应性(同步)

第一个看起来或多或少是这样的:

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
   }
}

非反应性方法如下:

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

为了不重新发明轮子或直接处理window对象或其他实现细节,我建议您引入另一层抽象通过使用角度材料CDK lib的LayoutModule

通过使用lib提供的BreakpointObserver,第二个实现将如下所示:

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

答案 1 :(得分:0)

您只需使用window.matchmedia检查设备的视口宽度,然后根据设备大小调用API。像这样 -

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