在发送GET或POST请求之前获取访问令牌

时间:2019-03-13 15:16:01

标签: angular ionic-framework ionic4

我正在尝试访问构造函数中的令牌,如下面的utils.service.ts文件中所示:

utils.service.ts>构造函数

storage.get('token').then((val) => {
  this.token = val;
  console.log("token: ", val);
});

我有所有需要令牌的api get和post请求。当我打如下电话时:

utils.service.ts

getDashboard() {
    if (this.dashboard) {
      return Promise.resolve(this.dashboard);
    }
    return new Promise(resolve => {
      this.http
        .get(globals.base_prod_api_url + "dashboard", {
          headers: {
            "Content-Type": globals.content_type,
            Authorization: "Bearer " + this.token
          }
        })
        .subscribe(
          data => {
            this.dashboard = data;
            resolve(this.dashboard);
          },
          error => {
            console.log(error);
            this.dashboard = error;
            return this.dashboard;
          }
        );
    });
  }

dashboard.page.ts

this.utilService.getDashboard().then(data => {
  this.dashboard_data = data;
});

甚至在从存储中检索令牌值之前,都会执行Get请求。 我如何先获取令牌,然后再向服务器发出获取请求?

3 个答案:

答案 0 :(得分:1)

我认为您应该使用拦截器来做到这一点。

首先,您必须将其添加到您的app.module.ts提供程序中:

  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpTokenInterceptor,
      multi: true
    },
    ...
  ],

然后拦截请求并将您的令牌添加到标头中:

import { Injectable, Inject } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpResponse } from '@angular/common/http';
import { JwtService } from '../services/jwt.service';

@Injectable({
 providedIn: 'root'
})
export class HttpInterceptorService implements HttpInterceptor {
  constructor(
    private jwtService: JwtService,
  ) {}

 public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

  const headersConfig = {
    'Accept': 'application/json',
  };

  storage.get('token').then((token) => {
      headersConfig['Authorization'] = `Bearer ${token}`;
      return next.handle(request.clone({
         setHeaders: headersConfig
      }));
  });
}

要走得更远,您可以使用拦截器来捕获错误:(例如,401用于处理刷新令牌)

return next
.handle(request.clone({
    setHeaders: headersConfig
}))
.pipe(
    catchError(err => {

        if (err.status === 401) {
            // token is no longer available, refresh it
        }

        return throwError(err);
    })
);

答案 1 :(得分:1)

您可以在 utils.service.ts 中创建一个私有异步方法。 如果令牌的值未定义,则它将令牌化并返回它。 例如:

$db = odbc_connect($dsn, $user, $pwd);

$query = odbc_exec($db, 'select * from GP_Vw_Cons_Faltas where DataInicio = "2018/11/28"
');

while($row = odbc_fetch_array($query)){
  echo "<pre>";
  print_r($row);
  echo "</pre>";
}

,并在标头对象中将其他方法标记为async和'await'。

例如

  async getToken(): Promise<string> {
    if(!this.token){
      this.token = await storage.get('token');
    }
    return this.token;
  }

答案 2 :(得分:1)

如果我是你,我会使用Observables而不是Promises。类似于RXJS 6

<iframe height="430" width="350" src="https://bot.dialogflow.com/xxxxxxxxxx">
  #document
  <!DOCTYPE html>
  <html>
    <head>
      <meta name="referrer" content="no-referrer" />
      <title>Small-Talk</title>
      <link
        rel="icon"
        type="image/png"
        href="https://console.dialogflow.com/api-client/assets/img/logo-short.png"
      />

      <meta property="og:title" content="Small-Talk" />
      <meta
        property="og:description"
        content="Allow your app to engage in small talk about a variety of topics."
      />
      <meta property="og:locale" content="en" />
      <meta property="og:image" content="" />

      <meta name="viewport" content="width=device-width, initial-scale=1" />
      <style>
        @-moz-keyframes blink {
          0% {
            opacity: 1;
          }
          50% {
            opacity: 0;
          }
          100% {
            opacity: 1;
          }
        } /* Firefox */
        @-webkit-keyframes blink {
          0% {
            opacity: 1;
          }
          50% {
            opacity: 0;
          }
          100% {
            opacity: 1;
          }
        } /* Webkit */
        @-ms-keyframes blink {
          0% {
            opacity: 1;
          }
          50% {
            opacity: 0;
          }
          100% {
            opacity: 1;
          }
        } /* IE */
        @keyframes blink {
          0% {
            opacity: 1;
          }
          50% {
            opacity: 0;
          }
          100% {
            opacity: 1;
          }
        } /* Opera and prob css3 final iteration */

        #preloader {
          background: #fff;
          position: fixed;
          top: 0;
          left: 0;
          height: 100%;
          width: 100%;
          z-index: 999999;
          opacity: 1;
          filter: alpha(opacity=100);
          -webkit-transition: opacity 500ms ease;
          transition: opacity 500ms ease;
        }

        #preloader .logo {
          display: block;
          width: 109px;
          height: 39px;
          background-repeat: no-repeat;
          background-image: url("https://console.dialogflow.com/api-client/assets/img/logo@2x-black.png");
          background-size: contain;
          position: absolute;
          top: 50%;
          left: 50%;
          margin: -20px 0 0 -55px;
          -moz-transition: all 1s ease-in-out;
          -webkit-transition: all 1s ease-in-out;
          -o-transition: all 1s ease-in-out;
          -ms-transition: all 1s ease-in-out;
          transition: all 1s ease-in-out;
          /* order: name, direction, duration, iteration-count, timing-function */
          -moz-animation: blink normal 2s infinite ease-in-out; /* Firefox */
          -webkit-animation: blink normal 2s infinite ease-in-out; /* Webkit */
          -ms-animation: blink normal 2s infinite ease-in-out; /* IE */
          animation: blink normal 2s infinite ease-in-out; /* Opera and prob css3 final iteration */
        }

        noscript h1 {
          padding: 20px;
        }
      </style>
      <!--[if lte IE 7]>
        <script src="https://assets.dialogflow.com/b/dialogflow_ui_20190207_1905_dumbledore_RC01/js/agentDemoApp/promise.min.js"></script>
      <![endif]-->
      <style>
        body {
          margin: 0;
          background: white;
        }
        audio {
          -webkit-transition: all 0.5s linear;
          -moz-transition: all 0.5s linear;
          -o-transition: all 0.5s linear;
          transition: all 0.5s linear;
          -moz-box-shadow: 2px 2px 4px 0px #006773;
          -webkit-box-shadow: 2px 2px 4px 0px #006773;
          box-shadow: 2px 2px 4px 0px #006773;
          -moz-border-radius: 7px 7px 7px 7px;
          -webkit-border-radius: 7px 7px 7px 7px;
          border-radius: 7px 7px 7px 7px;
          float: right;
          margin-right: 15px;
        }
        form {
          margin: 0;
        }
        .b-agent-demo {
          font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif;
          font-weight: 300;
          width: 100%;
          height: auto;
          color: #2b313f;
          font-size: 12px;
          overflow: hidden;
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
        }
        .b-agent-demo .user-request,
        .b-agent-demo .server-response {
          display: inline-block;
          padding: 15px 25px;
          border-radius: 3px;
          border: 1px solid #eee;
          margin-bottom: 5px;
          font-size: 16px;
          clear: both;
        }
        .b-agent-demo .user-request.server-response-error,
        .b-agent-demo .server-response.server-response-error {
          background-color: #f76949;
        }
        .b-agent-demo .user-request {
          background-color: #efefef;
          float: left;
          margin-right: 15px;
          margin-top: 15px;
          margin-left: 15px;
        }
        .b-agent-demo .server-response {
          color: #ffffff;
          background-color: #a5d175;
          float: right;
          margin-top: 15px;
          margin-right: 15px;
          margin-left: 15px;
        }
        .b-agent-demo .b-agent-demo_result {
          overflow-y: auto;
          background: white;
          position: fixed;
          top: 110px;
          bottom: 55px;
          width: 100%;
        }
        .b-agent-demo .b-agent-demo_result-table {
          height: 100%;
          min-height: 100%;
          width: 100%;
        }
        .b-agent-demo .b-agent-demo_result-table td {
          vertical-align: bottom;
        }
        .b-agent-demo .b-agent-demo_header {
          min-height: 80px;
          height: 80px;
          overflow: hidden;
          position: fixed;
          top: 0;
          width: 100%;
          background-color: #2b303e;
          display: table;
        }
        .b-agent-demo .b-agent-demo_header-wrapper {
          display: table-cell;
          vertical-align: middle;
        }
        .b-agent-demo .b-agent-demo_header-icon {
          position: absolute;
          top: 20px;
          left: 20px;
          width: 40px;
          height: 40px;
          border-radius: 100%;
          /*background-color: @response-color;*/
          overflow: hidden;
          vertical-align: middle;
          text-align: center;
        }
        .b-agent-demo .b-agent-demo_header-icon img {
          max-height: 100%;
          max-width: 100%;
          width: auto;
          height: auto;
          position: absolute;
          top: 0;
          bottom: 0;
          left: 0;
          right: 0;
          border: 0;
          margin: auto;
        }
        .b-agent-demo .b-agent-demo_header-agent-name {
          padding-left: 80px;
          font-size: 18px;
          color: #ffffff;
        }
        .b-agent-demo .b-agent-demo_header-description {
          color: #b7bbc4;
          padding-left: 80px;
          padding-top: 7px;
          font-size: 12px;
          display: block;
          /* Fallback for non-webkit */
          display: -webkit-box;
          max-height: 24px;
          /* Fallback for non-webkit */
          margin: 0 auto;
          line-height: 1;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .b-agent-demo .b-agent-demo_input {
          position: fixed;
          bottom: 0;
          height: 55px;
          border-top: 1px solid lightgray;
          background-color: white;
          width: 100%;
        }
        .b-agent-demo #agentDemoForm {
          display: block;
          margin-left: 15px;
          margin-right: 55px;
        }
        .b-agent-demo #query {
          width: 100%;
          border: 0;
          font-size: 16px;
          font-weight: 300;
          margin: 0;
          height: 55px;
        }
        .b-agent-demo #query:focus {
          outline: none;
          outline-offset: 0;
        }
        .b-agent-demo .b-agent-demo_input-microphone {
          display: none;
          position: absolute;
          font-size: 20px;
          width: 54px;
          height: 54px;
          right: 0;
          bottom: 0;
          cursor: pointer;
          text-align: center;
          /* line-height: 30px; */
          line-height: 54px;
          background: white;
          color: #b7bbc4;
        }
        .b-agent-demo .b-agent-demo_input-microphone.active {
          color: #f76949;
        }
        .b-agent-demo .b-agent-demo_powered_by {
          position: fixed;
          left: 0;
          right: 0;
          top: 80px;
          height: 30px;
          background-color: #f8f8f8;
          vertical-align: middle;
        }
        .b-agent-demo .b-agent-demo_powered_by span {
          color: #b7bbc4;
          text-transform: uppercase;
          float: right;
          vertical-align: middle;
          line-height: 20px;
          margin-top: 5px;
          margin-right: 10px;
          font-size: 10px;
          margin-left: -10px;
        }
        .b-agent-demo .b-agent-demo_powered_by img {
          margin-top: 7px;
          height: 16px;
          margin-right: 20px;
          float: right;
          vertical-align: middle;
          border: 0;
        }
        .clearfix {
          clear: both;
        }
      </style>
    </head>
    <body>
      <div id="preloader" style="opacity: 0; display: none;">
        <noscript>
          <h1>This application does'not work without javascript</h1>
        </noscript>
        <div class="logo"></div>
      </div>

      <div class="b-agent-demo">
        <div class="b-agent-demo_header">
          <div class="b-agent-demo_header-icon">
            <div class="b-agent-demo_header-icon-align-helper">
              <img
                id="agent-avatar"
                src="https://www.gstatic.com/dialogflow-console/common/assets/img/logo-short.png"
                srcset="
                  https://console.dialogflow.com/api-client/assets/img/logo-short.png 2x,
                  https://console.dialogflow.com/api-client/assets/img/logo-short.png 1x
                "
              />
            </div>
          </div>
          <div class="b-agent-demo_header-wrapper">
            <div class="b-agent-demo_header-agent-name">Small-Talk</div>
            <div class="b-agent-demo_header-description">
              Allow your app to engage in small talk about a variety of topics.
            </div>
          </div>
        </div>
        <div class="b-agent-demo_powered_by">
          <a href="https://dialogflow.com" target="_blank">
            <img
              src="https://console.dialogflow.com/api-client/assets/img/logo-black.png"
            />

            <span>Powered by</span>
          </a>
        </div>
        <div class="b-agent-demo_result" id="resultWrapper">
          <table class="b-agent-demo_result-table">
            <tbody>
              <tr>
                <td id="result"></td>
              </tr>
            </tbody>
          </table>
        </div>
        <div class="clearfix"></div>
        <div class="b-agent-demo_input">
          <form id="agentDemoForm">
            <input
              type="text"
              name="q"
              id="query"
              placeholder="Ask something..."
            />
            <i
              class="b-agent-demo_input-microphone material-icons-extended"
              id="mic"
              style="display: block;"
              >mic</i
            >

            <!--div class="b-agent-demo_input-microphone material-icons-extended mic-black" id="mic"></div-->
          </form>
        </div>
      </div>

      <script>
        AGENT_LANGUAGE = "en";
        AGENT_AVATAR_ID = "";
        SERVICE_BASE_URL = "https://console.dialogflow.com/api-client/";

        // non-blocking CSS delivery

        var loadDeferredStyles = function() {
          var addStylesNode = document.getElementById("deferred-styles");
          var replacement = document.createElement("div");
          replacement.innerHTML = addStylesNode.textContent;
          document.body.appendChild(replacement);
          addStylesNode.parentElement.removeChild(addStylesNode);
        };

        var raf =
          window.requestAnimationFrame ||
          window.mozRequestAnimationFrame ||
          window.webkitRequestAnimationFrame ||
          window.msRequestAnimationFrame;

        if (raf) {
          raf(function() {
            window.setTimeout(loadDeferredStyles, 0);
          });
        } else {
          window.addEventListener("load", loadDeferredStyles);
        }

        window["addStyleString"] = function(str) {
          var node = document.createElement("style");
          node.innerHTML = str;
          document.head.appendChild(node);
        };
      </script>
      <script
        defer=""
        src="https://assets.dialogflow.com/b/dialogflow_ui_20190207_1905_dumbledore_RC01/js/bundles/agentDemo.bundle.min.js"
      ></script>
      <!-- Google Analytics -->
      <script>
        window.ga =
          window.ga ||
          function() {
            (ga.q = ga.q || []).push(arguments);
          };
        ga.l = +new Date();
        ga("create", "UA-50971730-1", "auto");
        ga("send", "pageview");
      </script>
      <script
        async=""
        src="https://www.google-analytics.com/analytics.js"
      ></script>

      <div>
        <link
          href="https://fonts.googleapis.com/css?family=Roboto:400,300&amp;subset=latin,cyrillic"
          rel="stylesheet"
          type="text/css"
        />
        <link
          href="https://fonts.googleapis.com/icon?family=Material+Icons+Extended"
          rel="stylesheet"
        />
        <link
          href="https://cdn.jsdelivr.net/fontawesome/4.6.3/css/font-awesome.min.css"
          rel="stylesheet"
          type="text/css"
        />
      </div>
    </body>
  </html>
</iframe>

或者,ES6 Promises装饰器:Async,Await将从根本上简化您的代码。只是不记得通过try / catch块来捕获被拒绝的承诺