嘿,我有一个Angular项目,我想通过发出发布请求将数据从表单发送到Elasticsearch。但是,我实现了一些组件,但是它不起作用。有人能帮我吗? 目前它可以编译而没有任何错误,但是如果我按下按钮,则什么也没有发生。
那是我的html文件
<div>
<input placeholder="Enter post" [(ngModel)]="posts.text"/>
<button type="button" (click)="create_Post()">Post</button>
</div>
然后我有一个帖子课
export class Posts {
text: string;
}
那是我的邮政服务课
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {catchError, map} from 'rxjs/operators';
import {throwError} from 'rxjs';
import {Posts} from './posts';
@Injectable({
providedIn: 'root'
})
export class PostCreateService {
constructor(private http: HttpClient) { }
createPost(posts: Posts[]) {
return this.http.post(`http://xx.xx.xx.xx:9200/users/_doc`, posts).
pipe(
map((data: any) => {
return data;
}), catchError( error => {
return throwError( 'Something went wrong!' );
})
);
}
}
最后一个是我的post组件类
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {PostCreateService} from './post-create.service';
@Component({
selector: 'app-post',
templateUrl: './post.component.html',
styleUrls: ['./post.component.css']
})
export class PostComponent implements OnInit {
posts: any = {};
constructor(private http: HttpClient, private createpost: PostCreateService) {}
create_Post(){
this.createpost.createPost(this.posts).subscribe((res)=>{
});
}
ngOnInit(): void {
}
}
编辑:我按注释中的说明进行了更改,现在我收到一个CORS错误“来自来源'http://localhost:4200'已被CORS政策阻止”
答案 0 :(得分:0)
要从开发模式下解决问题,您应该从代理开始。这是角度的一部分。
示例proxy.conf.json
{
"/rest/elastic/*": {
"target": "http://elastic.host.path",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
并提供命令
ng serve --proxy-config proxy.conf.json