【问题标题】:How can I recive a response data from an http request in Angular?如何从 Angular 中的 http 请求中接收响应数据?
【发布时间】:2022-01-14 17:27:19
【问题描述】:

我想从 get http 请求中读取响应,我的服务器使用 Javascript,我发送响应的部分是:

app.get('/getReport',function(req,res) {
  try {
    const data=fs.readFileSync('./report.txt', 'utf8')
    res.end(data)
  }
  catch (err) {
    res.end("File not found")
  }
})

如果我使用 Postman,我可以看到报告文件的内容。 我想在我的 Angular 前端阅读这段文字,所以我在 home.service.ts 中创建了这个函数:

   public getReport(){
   return this.http.get<any>(this.url+'/getReport').subscribe(data => {
    this.value = data;})        
  }

它不起作用。如何正确阅读我的内容?

【问题讨论】:

  • “它不起作用”是什么意思?
  • 它什么也没做,我看不到任何文字,它是空的
  • 你看,事情很少只是“不工作”。可能有一些错误消息,一些意外的值,一些失败的连接。请进一步调查错误本身,将其提交给我们,我们将尽力帮助修复它
  • 没有任何错误,只是没有读取我可以通过邮递员的查询 URL 读取的 html 响应
  • “It”和“read”太模棱两可了。抱歉,帮不上忙

标签: javascript node.js angular typescript httprequest


【解决方案1】:

检查您的setup。在获取 http 请求之前,您必须导入一些模块:

@NgModule({
  imports: [
    BrowserModule,
    // import HttpClientModule after BrowserModule.
    HttpClientModule,
  ],...

【讨论】:

  • 我已经以相同的方式导入它,并且已经在我的 home.service.ts 中发布并获取请求,它们运行良好,所以我认为问题尤其是这个。
【解决方案2】:

为了接收任何响应,您必须开始与订阅“getReport”方法的 API/服务器进行通信

您如何做到这一点?

您的 home.service.ts 中有该方法。

  1. 在您要加载报告的组件(即“home-component”)中注入该服务
// NOTE: Fit all the paths to your specific system
...
import { HomeService } from '../services/home.service';
...

@Component({
  selector: 'app-home-component',
  templateUrl: './home-component.html',
  styleUrls: ['./home-component.scss'],
})
export class HomeComponent {

public report;

 constructor(
...
    private homeService: HomeService,
...

  ) {}
  1. 订阅 homeService 的 observable 'getReport' 方法,获取想要的数据。 例如,像这样更改构造函数:
 constructor(
...
    private homeService: HomeService,
...

  ) {

       this.homeService.getReport
        .subscribe((_response) => {
           console.log(_response);
           this.report = _response;
           alert(this.report);
       });

}

【讨论】:

  • 我已经完成了所有这些想法,除了我的 home.component 方法上的 .subscribe 而不是我的 home.service 方法。所以写这个:async openReport(){ this.homeservice.getReport().subscribe((_report) =&gt; {this.report = _report;}) alert(this.report) } 但它不起作用,因为警报打印我:未定义。我也以这种方式写报告public report: any;,因为没有 :any 它会给我一个错误。
  • 不要混用“可观察订阅”和“异步/等待”...尝试以我的简单回答方式进行操作。我已在正确的位置添加了警报。如果你的后台/API 工作正常并且编程正确,它就会工作!你会看到的! :)
  • 现在它没有给我任何警报
  • 控制台中的“console.log”显示什么?
  • 我应该看哪个控制台?我写“ng serve”的那个?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2011-03-03
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
相关资源
最近更新 更多