首页 > 解决方案 > 我可以在不使用角度 2+ 的 cookie 的情况下将 json 对象发送到 restApi

问题描述

我正在尝试将 json 类型的对象发送到(angular2+ springMvc + java)Web 项目中的其余服务,但这似乎很困难。我也不能使用cookie。

标签: angularrestspring-boot

解决方案


正如我从您的问题中得到的那样,您正试图找出一种方法来处理您的 Angular 项目中的 http 请求。

让我们先看看你的项目结构。您必须有一个单独的目录,其中包含与给定模块相关的所有服务。

在该目录中,您可以使用ng g s service-nameand 在这种情况下创建服务来处理 http 请求。

import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {environment} from "../../../../environments/environment";

const BASE_URL = environment.API_PATH;
const WAR = environment.API_WAR;

@Injectable({
  providedIn: 'root'
})
export class ServiceNameService {
  httpOptions = {
    headers: new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': 'my-auth-token'
    })
  };

  constructor(private http: HttpClient) {
  }

  getCall() {
    return this.http.get(`${BASE_URL}/${WAR}/your/path/all`);
  }

  getByIdCall(id) {
    return this.http.get(`${BASE_URL}/${WAR}/your/path?id=${id}`);
  }

  deleteByIdCall(id) {
    return this.http.delete(`${BASE_URL}/${WAR}/your/path/delete?id=${id}`);
  }

  postCall(payload: any) {
    return this.http.post(`${BASE_URL}/${WAR}/your/path/save`, payload);
  }

  putCall(id, payload) {
    return this.http.put(`${BASE_URL}/${WAR}/your/path/update?id=${id}`, payload);
  }

}

现在你必须在组件中调用它,你想要执行 http 请求。

import {Component, OnInit} from '@angular/core';
import {ServiceNameService} from '../../../services/http-services/service-name.service';

@Component({
  selector: 'app-config-view',
  templateUrl: './config-view.component.html',
  styleUrls: ['./config-view.component.scss']
})
export class ConfigViewComponent implements OnInit {

  constructor(private serviceNameService: ServiceNameService) {
  }

  ngOnInit() {
  }

  loadAll() {
    this.serviceNameService.getCall()
      .subscribe((data: any) => {
          console.log(data);
        }, error => {
          console.log(error);
        }
      );
  }

  loadById(id) {
    this.serviceNameService.getByIdCall(id)
      .subscribe((data: any) => {
          console.log(data);
        }, error => {
          console.log(error);
        }
      );
  }

  deleteById(id) {
    this.serviceNameService.deleteByIdCall(id)
      .subscribe((data: any) => {
          console.log(data);
        }, error => {
          console.log(error);
        }
      );
  }

  save() {
    const payload = {
      test: "test value"
    }
    this.serviceNameService.postCall(payload)
      .subscribe((data: any) => {
          console.log(data);
        }, error => {
          console.log(error);
        }
      );
  }

  update() {
    const payload = {
      test: "test value updated"
    }
    this.serviceNameService.putCall(id, payload)
      .subscribe((data: any) => {
          console.log(data);
        }, error => {
          console.log(error);
        }
      );
  }

}

现在您可以根据需要调用这些方法。

希望这可以帮助!

祝你好运!!


推荐阅读