Search code examples
htmlangulartypescriptionic2

return a dictionary of dictionaries flask and angular


I am creating an app using flask and ionic(angular) and I am trying to return a JSON of the list currently my python code is the following

def get-stocks():
# Select all stocks 
cursor.execute("""SELECT * FROM `tbl_symbol_index`""")
stocks = cursor.fetchall()
stockList = []
data = {}
for stock in stocks:
    symbol = stock[0]
    companyName = stock[1]
    stockList.append({
        "symbol": symbol,
        "companyName": companyName
    })
data = {'stocks': stockList}
print(len(data["stocks"]))
return jsonify(data)

This returns the following dictionary.

data = {"stocks": [
         "Symbol": "TSLA",
         "companyName": "Tesla Inc"
          ],
          [
         "Symbol": "MSFT",
         "companyName": "Microsoft"
          ],
          [
         "Symbol": "AAPL",
         "companyName": "Apple"
          ],
}

I call that function from my angular using

ngOnInit() {
// Get a list of all existing stocks
const Stocks = this.initializeItems();

}

  async initializeItems(){
    this.http.get("http://127.0.0.1:5000/get-stocks").subscribe(function(data) {
    })
  }

but for some reason I cannot loop through it in my HTML

<ion-list>
  <ion-item *ngFor="let data of Stocks | filter:filterTerm">
    <ion-label>{{data.symbol}}</ion-label>
    <ion-label>{{data.companyName}}</ion-label>
  </ion-item>
</ion-list>

Solution

  • Can you try this :

    @Component(...)
    export class Component {
     data;
     ngOnInit() {
      // Get a list of all existing stocks
      this.initializeItems();
     }
     initializeItems(){
        this.http.get("http://127.0.0.1:5000/get-stocks").subscribe(datas => {
           this.data = datas;
            console.log(this.data.stocks)
        });
      }
    }