2017-09-29 52 views
0

我正在將AngularJS v1.5項目升級到Angular 4.x。在開發原始AngularJS應用程序的過程中,我們將使用ngMocks包來模擬實際的Web服務API響應,並在頁面上顯示相應的數據。這在開發過程中非常有用,因爲我以後不需要對值進行硬編碼。最重要的是,我們將Webpack配置爲在開發過程中僅包含模擬數據,並且在構建我們的應用程序以供生產使用時忽略這些模擬數據文件。模擬數據配置是這樣的:那麼Angular 4 - 如何模擬原型和開發的模擬數據

/* app-login.mock.js */ 
import angular from 'angular'; 
import 'angular-mocks'; 

angular.module('app').run(function ($httpBackend) { 
    $httpBackend 
     .whenPOST('./api/auth') 
     .respond(function(method, url, data) { 
      var credentials = angular.fromJson(data); 
      if (credentials.username == 'gooduser') { 
       return [200, {'token': createToken(credentials.username)}]; 
      } else { 
       return [401, {'errorMsg': 'Mock login only allows username "gooduser"'}]; 
      } 
     }); 
}); 

function createToken(username) { 
    // Create a token, which is valid enough for testing purposes. 
    // This token is based on the actual token generated by the web service. 
    let currentTime = new Date(); 
    let futureTime = new Date(currentTime.getTime() + ((currentTime.getHours() + 8) * 60 * 60 * 1000)); 

    let header = { 
     alg: 'HS512' 
    }; 

    let payload = { 
     exp: futureTime.getTime()/1000, 
     sub: username, 
     roles: 'SOME_APPLICATION_ROLES', 
     iat: currentTime.getTime()/1000 
    }; 

    return `${btoa(angular.toJson(header))}.${btoa(angular.toJson(payload))}`; 
} 

的WebPack被配置爲包括所有「模擬」文件到內置捆綁,就好像它是一個真正的HTTP響應可能隨後被顯示出來。

/* webpack.config.js */ 
const isProd = process.env.NODE_ENV === 'production'; 

const entry = { 
    app: (() => { 
     let app = [ 
      'babel-polyfill', 
      path.join(PATHS.app, 'pollyfills.ts'), 
      path.join(PATHS.app, 'main.ts') 
     ]; 

     if (isProd) { 
      app.push(path.join(PATHS.app, 'app.prod.js')); 
     } else { 
      app.push(path.join(PATHS.app, 'app.mock.js')); 
     } 

     return app; 
    })() 
}; 

module.exports = { 
    entry, 
    // ...other exports 
}; 

然後是app.mock.js文件:

/* app.mock.js */ 
var mockContext = require.context(".", true, /\.mock$/); 
mockContext.keys().forEach(mockContext); 

我已經沖刷互聯網尋找的作品一樣好,我們的舊的解決方案,雖然我還沒有想出什麼好答案。我發現的最好的教程是關於如何設置返回模擬數據的單元測試,雖然這對於測試功能非常有用,但它並不能幫助我在開發過程中測試應用程序。

我也看到了有關使用內4角新發現的HttpClient類設置Interceptors一些文檔,但我不知道如何將它添加到我們的WebPack配置的開發過程中只被允許的情況下。有沒有人有什麼建議做什麼?

+0

你試過JSON-服務器。我在我們的應用程序中使用它 – Skeptor

+0

我從來沒有聽說過它,但我會看看自己。感謝您的建議! –

回答

2

我使用角內存中的web-api。你可以在這裏找到它:https://github.com/angular/in-memory-web-api

它攔截所有的http調用,並與你提供的示例數據一起工作。

要從dev切換到生產,您需要刪除導入。或者你可以編寫兩個不同的模塊,一個使用dev進口,一個使用生產導入,另一個模塊包含一個或另一個與webpack相似的模塊。 (但我沒有試過。)

你建立你的數據是這樣的:

import { InMemoryDbService } from 'angular-in-memory-web-api'; 

import { IProduct } from './product'; 

export class ProductData implements InMemoryDbService { 

    createDb() { 
     let products: IProduct[] = [ 
      { 
       'id': 1, 
       'productName': 'Leaf Rake', 
       'productCode': 'GDN-0011', 
       'releaseDate': 'March 19, 2016', 
       'description': 'Leaf rake with 48-inch wooden handle.', 
       'price': 19.95, 
       'starRating': 3.2, 
       'imageUrl': 'http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png', 
       'tags': ['rake', 'leaf', 'yard', 'home'] 
      }, 
      // ... 
     ]; 
     return { products }; 
    } 
} 

你使用普通的HTTP或HttpClient的建立自己的數據訪問服務。

我有一個完整的例子在這裏所有的CRUD操作:https://github.com/DeborahK/Angular2-ReactiveForms