美文网首页
angular原生http请求

angular原生http请求

作者: LeeYaMaster | 来源:发表于2020-04-23 20:09 被阅读0次

    第一,首先是Http文件负责最主要的请求:

    import {Injectable} from '@angular/core';
    import {NzMessageService} from 'ng-zorro-antd/message';
    import {HttpClient, HttpHeaders} from '@angular/common/http';
    import {Config} from './config';
    import {Router} from '@angular/router';
    
    @Injectable()
    export class Http {
      constructor(public msg: NzMessageService, public httpClient: HttpClient, private router: Router) {
    
      }
      const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type':  'application/json',
            'token': localStorage.getItem('token')
          })
        };
        this.httpClient.post( Config.API_URL + url, data, httpOptions,
        ).subscribe((result: ValueObject) => {
          console.log(result);
          if (result.status == -2){
              this.msg.error('token过期,请重新登录');
              this.router.navigate(['login']);
          }
          return callbackFun(result);
        }, error => {
          callbackFun(error);
        });
      }
    }
    
    interface ValueObject {
      status?: number
    }
    
    

    其次是service文件:

    import {Injectable} from '@angular/core';
    import {Http} from './http';
    
    /**
     * 用户登录服务
     */
    import {Http} from './http';
    @Injectable()
    export class Service {
      constructor(private http: Http) {}
    
      // 分类
      test(data, callbackFun) {
        this.http.request('xxx/xxx',
          data
          , callbackFun);
      }
    }
    
    

    第三才是业务:

    import {Service} from '../service/service';
    export class Xxxx implements OnInit {
     constructor(private service: Service) {
        this.getAllData();
      }
      getAllData(){
        this.service.getAllProduct(null, (result) => {
            console.log(result);
        });
      }
    }
    

    图片上传:

          const file = Imageinput.files[0];
          const data: FormData = new FormData();
          data.append('file', file, file.name);
          const header = new Headers();
          header.append('Accept', 'application/json');
          this.httpClient.post(Config.API_URL + 'xxx', data)
              .subscribe((res) => {
                console.log(res);
              });
          
    

    相关文章

      网友评论

          本文标题:angular原生http请求

          本文链接:https://www.haomeiwen.com/subject/vlntvhtx.html