【问题标题】:what is best way to store API Urls and use in angular什么是存储 API Urls 并在 Angular 中使用的最佳方法
【发布时间】:2020-01-27 09:47:49
【问题描述】:

我想将所有 API URL 存储在一个地方,即 JSON 文件中,我想在整个应用程序中使用该 JSON 文件。

i) 保存 JSON 文件的最佳位置是什么。 ii) 如何使用 Type 脚本文件中的 URLs

【问题讨论】:

  • 为什么不直接使用普通的打字稿文件来存储所有的 url 并调用它(比如)api-urls.ts?
  • @Nicolas K- 因此可以在生产期间对其进行编辑,而无需重新构建或发布

标签: angular


【解决方案1】:

我会将基本 url 存储在 environment.ts 中

export const environment = {
  production: false,
  baseUrl: 'http://example.com/api'  
};

对于 api URL,我会创建一个枚举:

export enum ApiPaths {
   Auth = '/auth',
   Foo = '/foo',
   Bar = '/bar'
}

然后在服务中使用:

import { environment } from '../environments/environment';
import { ApiPaths } from '../enums/api-paths';

@Injectable()
export class FooService {  

  baseUrl = environment.baseUrl;

  constructor(private httpClient: HttpClient) { }

  getAll() {
    let url = `${this.baseUrl}/${ApiPaths.Foo}/all`;
    return this.httpClient.get<JSON>(url);
  }
}

【讨论】:

    【解决方案2】:

    提供的其他答案提供了存储和访问基本 url 的好方法,我个人将其存储在 environment.ts 并插入到来自 HttpInterceptor 的请求中。

    我想在您的问题中尝试解决的是在基本 url 之后管理端点。这是我希望看到更好的解决方案,但这是我目前使用的。

    在对 API 进行 http 调用的每个 Angular 服务中,我都有一个如下属性:

    private readonly API_ROUTES = {
      getUser: (userId: string) => `/user/${userId}`
    }
    

    这适用于我的传递参数的方法,如果你使用查询参数,那么你可以调整它来处理。

    然后对应的方法就可以用这个了:

    public getUser(userId: string): Observable<User> {
      return this.http.get<User>(this.API_ROUTES.getUser(userId));
    }
    

    完整的示例类:

    import { Injectable } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class UserService {
    
      private readonly API_ROUTES = {
        getUser: (userId: string) => `/user/${userId}`
      }
      
      constructor(private http: HttpClient) { }
    
      public getUser(userId: string): Observable<User> {
        return this.http.get<User>(this.API_ROUTES.getUser(userId));
      }
    
    }
    

    这显然可以被进一步提取以将所有 API 路由放在一个文件中的某个位置,正如其他人所建议的那样,它可能只是 api-routes.ts。

    我希望其他人可能有更好的模式,因为我觉得这不是最好的解决方案。

    【讨论】:

      【解决方案3】:

      在我们的项目中,我们为开发、生产、登台制作了不同的环境文件 喜欢

      环境.dev.ts

      环境.staging.ts

      环境.prod.ts

      我们使用 package.json 脚本来获取需要加载的 api url

      "scripts": {
      "ng": "ng",
      "start:dev": "ng build --prod -c=dev",
      "start:qa": "ng build --prod -c=qa",
      }
      

      所以它会加载所需的 api

      示例服务文件

      import { Injectable } from '@angular/core';
      import { AuthService } from 'src/app/auth.service';
      import { HttpClient, HttpHeaders } from '@angular/common/http';
      import { environment } from 'src/environments/environment';
      
      @Injectable({
        providedIn: 'root'
      })
      export class NetworkService {
        private apiUrl: string = environment.BASE_URI;
        options;
        constructor(private authService: AuthService, private http: HttpClient) {}
      
        updateNetwork(formValue) {
          this.authService.loadToken();
          const headers = new HttpHeaders().set(
            'Authorization',
            `Bearer ${this.authService.authToken}`
          );
          formValue.nor_id = this.authService.getNorId();
          return this.http.post(`${this.apiUrl}/recipe/network`, formValue, {
            headers
          });
        }
      }
      

      【讨论】:

      • 我喜欢这个主意,因为您发布此内容已经有一段时间了,您能否告诉我它对您的效果如何?您是否在执行此方法时遇到任何挫折或后来最终更改它,或者此方法是否有效并且您仍然建议在替代方案中执行此操作?谢谢!
      猜你喜欢
      • 2017-02-22
      • 2013-02-15
      • 2010-12-16
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 2016-12-22
      • 1970-01-01
      相关资源
      最近更新 更多