使用Angular 5和HTTPClient调用REST POST API

问题描述 投票:1回答:2

我正在使用Angular为我的后端创建前端,并且使用HTTPClient调用POST API时遇到了麻烦。以下是我的代码:

article.service.ts

@Injectable()
export class ArticleService {
    url = "//localhost:8080/deleteArticle";
    constructor(private http: HttpClient) { }

    deleteArticle(article: Article): Observable<HttpResponse<Article>> {
        return this.http.post<Article>(this.url, article,
            {
              observe: 'response'
            }
        );
    }
}

article.component.ts

@Component({
   selector: 'app-article',
   templateUrl: './article.component.html'
})
export class AcrticleComponent implements OnInit {
  articleForm: FormGroup;
  constructor(private formBuilder:FormBuilder, private articleService: ArticleService) {
  }
  ngOnInit() {
    this.articleForm = this.formBuilder.group({
      title: ['', [ Validators.required ] ]
    });
  }
  onFormSubmit() {
    let article = this.articleForm.value;
    this.deleteArticle(article);
    this.articleForm.reset();
  }
  deleteArticle(article: Article) {
    this.articleService.deleteArticle(article).subscribe(
      article => {
        console.log(article);
      },
      err => {
        console.log(err);
      }
    );
  }
  get title() {
     return this.articleForm.get('title');
  }
}

弹簧控制器:

    @PostMapping("/deleteArticle")
    @CrossOrigin(origins = "http://localhost:4200")
    public String deleteArticle(@RequestParam(value = "id") String id) {
        deleteService.deleteArticle(id);
    }

输入标题并点击提交后,它将返回此错误(状态404):

{error:“集合'localhost:8080'找不到”}

你能告诉我我做错了什么以及我的角度前端如何找不到我的后端端点吗?

spring angular rest angular-httpclient
2个回答
1
投票

网址需要完整。包括http:

但我建议使用webpack dev服务器代理。

如果您将所有api放在/ api / url下,那么您可以将所有对/ api / *的调用代理回您的spring后端。

然后当你启动你的项目时,你在那里使用nginx或类似的/ api / *代理。

您可以在这里阅读更多关于如何使用angular-cli https://github.com/angular/angular-cli/wiki/stories-proxy进行代理的信息


0
投票

确保你的弹簧应用程序与8080在同一个端口上运行,并在你的http之前添加url。我希望这不是你的问题,但尝试这样..

@Injectable()
export class ArticleService {
    url = "http://localhost:4200/deleteArticle";//add http here
    constructor(private http: HttpClient) { }

    deleteAccount(article: Article): Observable<HttpResponse<Article>> {
        return this.http.post<Article>(this.url, article,
            {
              observe: 'response'
            }
        );
    }
}

编辑

添加一个类似Article并获得你从IdArticle发送的Angular Service

    @PostMapping("/deleteArticle")
    @CrossOrigin(origins = "http://localhost:4200")
    public String deleteArticle(@RequestParam() Article article,
                                RedirectAttributes redirectAttributes) {
        deleteService.deleteArticle(article.id, redirectAttributes);
    }
© www.soinside.com 2019 - 2024. All rights reserved.