简体   繁体   中英

Subscribing Observable from HTTP request

My Spring Boot controller sends String "hello Angular" as a simple response to http request.

@Controller
@RequestMapping(path = "/u")
public class UController {
    @RequestMapping("/greet")
        public  @ResponseBody  String greet() {
            System.out.println("you are in the method greet() ");
            return "hello Angular";
    }
}

I see at console (System.out) that Angular has requested right method and the response should have been sent to client.

I would like to print this message by Angular on the web site, so I subscribe the Observable from http client, but it does not appear on the screen.

Here is my Angular component:

import { Component, OnInit } from '@angular/core';
import { HttpClientModule }    from '@angular/common/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-root',
  template: `
    <div style="text-align:center">
      <h1> {{greeting}} </h1>
      </div>
    <router-outlet></router-outlet>
  `,
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit{

    greeting : string;

    constructor(private http: HttpClient){  }

    ngOnInit() {
        this.http.get<string>('http://localhost:8080/u/greet').subscribe(data => { this.greeting = data; });
    }
}

I really have no idea how can I fix it.

The error is happening because HttpClient assumes content to be valid JSON, not a simple string. It effectively attempts to parse JSON internally. If you try to do JSON.parse("hello Angular") , it will show the exact same error:

 JSON.parse("hello Angular"); 

To retrieve non-JSON content , you can do the following by specifying the response type to be text as well as removing the generic typing of <string> :

this.http.get('http://localhost:8080/u/greet', {responseType: 'text'})
  .subscribe(data => { this.greeting = data; });

Otherwise, for any actual JSON ( application/json ) data being returned from the server, you do not need to provide responseType and can/should use the generic typing mechanism.

Hopefully that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM