angular - 我可以在不使用角度 2+ 的 cookie 的情况下将 json 对象发送到 restApi
问题描述
我正在尝试将 json 类型的对象发送到(angular2+ springMvc + java)Web 项目中的其余服务,但这似乎很困难。我也不能使用cookie。
解决方案
正如我从您的问题中得到的那样,您正试图找出一种方法来处理您的 Angular 项目中的 http 请求。
让我们先看看你的项目结构。您必须有一个单独的目录,其中包含与给定模块相关的所有服务。
在该目录中,您可以使用ng g s service-name
and 在这种情况下创建服务来处理 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);
}
);
}
}
现在您可以根据需要调用这些方法。
希望这可以帮助!
祝你好运!!
推荐阅读
- php - 注销后如何在codeigniter中销毁sess_cookie_name
- javascript - 如何在jquery中使用.html(要显示的值)时在td元素中添加span元素
- html - AMP:为什么 .amp.html 扩展名的文件不显示在 linux 主机上?
- jquery - jQuery 拖放
- azure - v2.0 应用程序缺少 AppCatalog 资源权限
- php - 按可用性对可变产品进行排序
- java - 创建一个允许接收多个条目数据的程序,显示列表中的数据
- forms - 如何使用道具从子表单正确更新父组件
- java - JAVA 仅在获得值时保留小数位
- java - SmartLocationLibrary 位置始终为空