首页 > 解决方案 > Angular8 使用 HttpClient GET 方法从 Scala Play 端点检索连续数据

问题描述

我在将数据(连续)从 Scala Play 环境接收到 Angular 8 前端项目时遇到问题。对于更简单的数据样本(静态 jsons),访问数据(GET 和 POST 方法都没有参数)没有问题,但是当我尝试从 Scala 中实现的端点获取当前时间时,它就是不工作。正如我使用 curl 命令测试的那样,Scala 的代码可以正常工作,并返回预期的结果。

在 Angular 中,我有一项服务向 Scala 和我订阅服务功能的主要组件发出请求。应用服务.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { map } from 'rxjs/operators';
import { Observable } from 'rxjs/index';

@Injectable()
export class AppService {
  private getTime = '/api/liveClock';

  constructor(private http: HttpClient) {
  }

  public retrieveTime() {
    return this.http.get(this.getTime, {responseType: 'text'}).pipe(
      map(response => response)
    );
  }

app.component.ts

import { Component, OnInit } from '@angular/core';

import { AppService } from './app.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  constructor(private appService: AppService) {
    this.appService.retrieveTime().subscribe({
      next(t) { console.log('d:', t); },
      error(e) {console.log('error:', e); },
      complete() { console.log('Finished'); }
    });
  }

  onInit() {
  }
}

你对这项工作有什么建议吗?非常感谢!

标签: angularscala

解决方案


我找到了解决我的问题的方法 - 服务请求功能的不同实现:

public retrieveTime(): Observable<any> {
    const req = new HttpRequest(
      'GET', `${this.getTime}`, {responseType: 'text', reportProgress: true}
    );
    return this.http.request(req).pipe(
      map(response => response)
    );
  }

如果有人有不同的想法,请赐教:-)


推荐阅读