當咱們的項目運行在微信端時,用到oAuth第三方認證。問題來了,在ng4中微信認證應該放在哪裏呢?html
開始項目的時候,我將oAuth認證放在了每一個頁面模版中,發現返回歷史頁的時候,須要返回兩次。bootstrap
這個問題應該是認證的時候跳轉頁面致使的,因此,咱們要考慮將oAuth放到合適的位置去。api
下面具體的來講一說oAuth在ng4的步驟。微信
1、引入oauth.js文件app
將oauth.js文件放在「assets」文件夾下,而後在index.html裏面引入ssh
<script src="assets/js/oauth.js"></script>
2、聲明變量oAuthangular4
這一步很關鍵,由於引入的js文件中的對象oAuth,並不能被ng識別,因此咱們須要先聲明oAuth。學習
在typings.d.ts中全局申明oAuth變量ui
declare var oAuth: any;
3、在main.ts實現oAuth微信認證spa
爲何在main.ts中實現認證?main.ts負責引導整個angular應用的起點。具體請移步我寫的《angular4.0項目main.ts詳解》中去學習吧。
實現微信認證請看下面的代碼,核心是:在微信認證完成後的回調中,執行 platformBrowserDynamic().bootstrapModule(AppModule);
import { enableProdMode } from '@angular/core'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; import { environment } from './environments/environment'; if (environment.production) { enableProdMode(); } //微信oauth認證 oAuth.cfg(Config.uid, Config.isDebug, Config.scope); oAuth.checkToken((apiopenid, apitoken) => { Config.apiopenid = apiopenid; Config.apitoken = apitoken; //認證完成後,調用bootstrapModule方法來傳入AppModule做爲啓動模塊來啓動應用。 platformBrowserDynamic().bootstrapModule(AppModule); });
ok,就這樣完成了,謝謝大嬸指點。