代码之家  ›  专栏  ›  技术社区  ›  Lasitha Yapa Programmer

如何向http拦截器添加加载程序

  •  1
  • Lasitha Yapa Programmer  · 技术社区  · 7 年前

    我正在做一个ReactJS项目,它严重依赖于一些api。
    我有一个HTTP服务,所有组件都使用它来调用api。
    我需要添加一个加载程序,以便在处理某个HTTP请求时显示它。
    目前我正在使用redux状态来打开和关闭加载程序。由于我无法从服务中更改redux状态,所以当我使用http调用时,我当前正在从组件中调用加载程序on/off。
    我需要实现的是从服务本身打开/关闭加载程序,这样每当我使用HTTP服务时就不必考虑它。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Asif vora    7 年前

    如果你想要整个页面加载程序,这样你就可以管理它的外观。您可以直接从您的HTTP调用方法中显示hide loader。

    HttpRequests.js文件

       'use strict';
    
       function isLoaderManage() {
         let x = document.getElementById("loader");
          if (x.style.display === "none") {
             x.style.display = "block";
           } else {
            x.style.display = "none";
           }
        }
    
        const request = {
            get: (url) => {
                return fetch(url)
                    .then((resp) => {
                        isLoaderManage();
                        return resp.json();
                    })
                    .then((resp) => {
                        isLoaderManage();
                        return resp;
                    }).catch((err) => {
                        isLoaderManage();
                        return err;
                    });
            },
        }
    
        export { request };
    

    'use strict';
    
    import { request } from './HttpRequests';
    
    const API = {
        getSongs: (URL) => request.get(URL),
    }
    
    export { API };
    

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <base href="/" />
        <meta charset="utf-8">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>React App</title>
    </head>
    
    <body>
        <noscript>
            You need to enable JavaScript to run this app.
        </noscript>
        <div id="loader"></div>
        <div id="root"></div>
    </body>
    
    </html>
    

    索引.css

    #loader {
      position: fixed;
      width: 100%;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      background-color: rgba(255, 255, 255, 0.7);
      z-index: 9999;
    }
    
    @-webkit-keyframes spin {
      from {
        -webkit-transform: rotate(0deg);
      }
      to {
        -webkit-transform: rotate(360deg);
      }
    }
    
    @keyframes spin {
      from {
        transform: rotate(0deg);
      }
      to {
        transform: rotate(360deg);
      }
    }
    
    #loader::after {
      content: "";
      display: block;
      position: absolute;
      left: 48%;
      top: 40%;
      width: 40px;
      height: 40px;
      border-style: solid;
      border-color: black;
      border-top-color: transparent;
      border-width: 4px;
      border-radius: 50%;
      -webkit-animation: spin 0.8s linear infinite;
      animation: spin 0.8s linear infinite;
    }
    
    推荐文章