Getting a string value from flask using angular

Viewed 35

I know that there are a lot of tutorials available which show how to connect to flask via angular. However, I am not successful with displaying a simple string fetched from flask and ask you kindly to have a look at my code. What I can tell is that I can start the Flask server and I am also able to see the string in the browser, if I directly connect to the Flask port. The problems start with angular.

Here is the short Flask code:

app = Flask(__name__)
@app.route('/')
def fetch_acceleration_data():
    return "hallo"

The server runs on port 5000 on the local host. In angular, I have this service:

    import {Injectable} from '@angular/core';
import {HttpClient, HttpErrorResponse} from '@angular/common/http';
import {Observable, tap} from 'rxjs';
import {environment} from '../environments/environment.prod';
import { ACC } from './flaskcon';

@Injectable()
export class testService {
    constructor(private http: HttpClient) {
    }

    getAcc(): Observable<any> {
      return this.http.get(environment.apiURL);
      }
}

getAcc is meant to get the string value. The environment is specified like this:

export const environment = {
  production: true,
  apiURL: 'http://127.0.0.1:5000'
};

In my app component, I have the method gnOnInit:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription, tap } from 'rxjs';
import { ACC } from './flaskcon';
import { testService } from './flaskcon.service';

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

export class AppComponent implements OnInit, OnDestroy {
  title = 'test';
  accListSubs: Subscription;
  accList: string;

  constructor(private accAPI: testService) {
  }

  ngOnInit() {
    this.title = 'anders'
    this.accListSubs = this.accAPI
      .getAcc().subscribe((res:any) => {
        this.accList = res;
      }
      );
  }

  ngOnDestroy(): void {
    this.accListSubs.unsubscribe();
  }
}

As I understand it, accList should store the string from flask. But "res" ist always undefined. Interestingly, there is a http request shown in the flask server log, which indicates a successful get request with code 200.

I am sorry for the variable names. Later, I want to transfer acceleration values from a database. As I got these problems, I first tried to transfer a simple string.

0 Answers
Related