天天看點

SAP Spartacus OccEndpointsService getUrl方法的實作原理

源代碼:

/**

  * Returns a fully qualified OCC Url (including baseUrl and baseSite)

  * @param endpoint Name of the OCC endpoint key config

  * @param urlParams  URL parameters

  * @param queryParams Query parameters

  * @param scope

  */

 getUrl(

   endpoint: string,

   urlParams?: object,

   queryParams?: object,

   scope?: string

 ): string {

   endpoint = this.getEndpointForScope(endpoint, scope);

   if (urlParams) {

     Object.keys(urlParams).forEach((key) => {

       urlParams[key] = encodeURIComponent(urlParams[key]);

     });

     endpoint = DynamicTemplate.resolve(endpoint, urlParams);

   }

   if (queryParams) {

     let httpParamsOptions = { encoder: new HttpParamsURIEncoder() };

     if (endpoint.includes('?')) {

       let queryParamsFromEndpoint;

       [endpoint, queryParamsFromEndpoint] = endpoint.split('?');

       httpParamsOptions = {

         ...httpParamsOptions,

         ...{ fromString: queryParamsFromEndpoint },

       };

     }

     let httpParams = new HttpParams(httpParamsOptions);

     Object.keys(queryParams).forEach((key) => {

       const value = queryParams[key];

       if (value !== undefined) {

         if (value === null) {

           httpParams = httpParams.delete(key);

         } else {

           httpParams = httpParams.set(key, value);

         }

       }

     const params = httpParams.toString();

     if (params.length) {

       endpoint += '?' + params;

   return this.getEndpoint(endpoint);

 }

入口:

SAP Spartacus OccEndpointsService getUrl方法的實作原理
SAP Spartacus OccEndpointsService getUrl方法的實作原理
SAP Spartacus OccEndpointsService getUrl方法的實作原理

一個具體的例子:

https://spartacus-dev0.eastus.cloudapp.azure.com:9002/occ/v2/electronics-spa/products/300938?fields=code,name,summary,price(formattedValue),images(DEFAULT,galleryIndex)&lang=en&curr=USD

從浏覽器裡得到的結果:

SAP Spartacus OccEndpointsService getUrl方法的實作原理

繼續閱讀