Implementing Data Binding with Ajax Responses in Angular 2 TypeScript Using the FetchApi Method

I am working on my first angular2 application with typescript. I have successfully fetched results using fetchApi but I am struggling to display them in the views. Can someone please guide me on how to present my data in the views? Thank you.

App.components.ts

///<reference path="../node_modules/angular2/typings/browser.d.ts"/>
import {Component} from "angular2/core";

import {Mallspk} from './mallspk'
import {NgFor} from "angular2/common";
export class Hero{
    id:number;
    name:string;
}



@Component({
    selector: 'my-app',
    template: '<input type="text" [(ngModel)]="title" /><h1>{{title}}</h1>'
})
export class AppComponent
{
    title="Tour of Heroes";
    hero: Hero={
        id:1,
        name:"Qasim"
    };
}


@Component({
    selector:"my-app-selector",
    bindings:[Mallspk],
    template:`
  <input type="search" [(ngModel)]="search" #photoQuery />

  <button (click)="searchPhotos(photoQuery.value)">Search photos</button>
  <ul>

    <li *ngFor="#photo of photos">
        <table>
            <tr>
                <td>
                    {{photo.title}}
                </td>
                <td>
                    photo.isActive
                </td>
                <td>
                   <img [src]="photo.imageUrl" width="250px">
                </td>
            </tr>
        </table>

    </li>
  </ul>
  `,
    directives: [NgFor]
})

export class PhotoView{
    mallspk=null;
    photos=null;
    search=null
    constructor(mallspk:Mallspk){
        this.mallspk=mallspk;
        this.search="text"
    }

    searchPhotos(query){
        this.mallspk.searchPhotos(query).then((photos)=>{
            console.log(photos);
            this.photos=photos.data.collection.brands;
        });
    }
}

main.ts

import {bootstrap} from "angular2/platform/browser";
import {AppComponent, PhotoView} from "./app.components";

bootstrap(AppComponent);
bootstrap(PhotoView)

insex.html

<html>
<head>
    <title>Angular 2 QuickStart</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="style.css">
    <!-- 1. Load libraries -->
    <!-- IE required polyfills, in this exact order -->
    <script src="node_modules/es6-shim/es6-shim.min.js"></script>
    <script src="node_modules/angular2/es6/dev/src/testing/shims_for_IE.js"></script>

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>
    <!-- 2. Configure SystemJS -->
    <script>
        System.config({
            packages: {
                app: {
                    format: 'register',
                    defaultExtension: 'js'
                }
            }
        });
        System.import('app/main')
                .then(null, console.error.bind(console));
    </script>
</head>
<!-- 3. Display the application -->
<body>
<my-app>Loading...</my-app>
<br>
<my-app-selector></my-app-selector>
</body>
</html>

mallspk.ts

declare var fetch;
export class Mallspk{
    searchPhotos(query) {
        return fetch(`http://www.malls.pk/api/index.php/malls/mall?city_name=Lahore&city_name=Lahore&lat=12&lng=23`).then(function(response) {

            return response.json();
        });
    }

}

Answer №1

It appears that the mistake lies here:

this.mallspk.searchPhotos(query).then((photos)=>{
  this.photos = photos.data.collection.brands; <== collection isn't contained property brands
});

Consider modifying the code as follows:

this.photos = photos.data.collection;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with initial navigation in MVC app causing Angular app routing to fail

Encountering a problem with navigating within an Angular app hosted on an MVC page. While most of the functionality is working smoothly, there is one scenario where the URL changes but the new page is not displayed. Let's simplify the setup (this iss ...

Halt the flow of a pipe midway through

Within my Angular application, there exists a token refresh interceptor designed to catch 401 Unauthorized errors. The interceptor then attempts to refresh an access token and resubmit the original HTTP request. There are scenarios where the token refresh ...

Angular Error cli command Error: In order to proceed, please provide a command. To see a list of available commands, use '--help'

When I run any command with Angular CLI, I encounter an error. To resolve this issue, I attempted to uninstall and reinstall it by running the following commands: npm uninstall -g @angular/cli npm install -g @angular/cli However, the problem persists an ...

Is it necessary to unsubscribe from an Angular HTTP-Request when using switchMap?

I have a question about managing subscriptions in my Angular application. I'm currently using the combineLatest operator to create an observable from two Angular observables, route.params and route.queryParams. This combined observable is then used as ...

Issue encountered while deploying Next.js application on vercel using the replaceAll function

Encountering an error during deployment of a next.js app to Vercel, although local builds are functioning normally. The issue seems to be related to the [replaceAll][1] function The error message received is as follows: Error occurred prerendering page &q ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

Encountering error TS2305 in Visual Studio Code while working with moment.js in an example from an Angular Material

After referencing the code snippet from https://material.angular.io/components/datepicker/overview#choosing-a-date-implementation-and-date-format-settings, I encountered an issue. While the code successfully compiles and runs, Visual Studio Code flagged an ...

Errors related to Angular are now being displayed in VS Code following an update, although the build process itself

After updating Angular, I've noticed that VS Code is showing errors in my HTML files even though there are no actual errors present. Interestingly, ng build and ng serve are both working without any issues. Below are some screenshots for reference. Ca ...

Using TypeScript to pass the text field ID to a function for clearing the text field with a button

I am looking for a way to improve the functionality of my web page featuring several buttons that will clear different text boxes on the same line. Currently, I am using separate functions for each button, but my goal is to streamline this process by utili ...

Filter for the final item in Angular

Is there a way to create a filter that specifically retrieves the last element from a list? Alternatively, how can I implement a filter that excludes the last element? Context: I've got a list of items and I need to make sure the last item is editabl ...

Avoid invoking a TypeScript class like a regular function - _classCallCheck prevention

I am currently developing a TypeScript library that needs to be compatible with all versions of JavaScript. I have noticed that when calling a class in TS without using new, it does not compile properly, which is expected. In ES6/Babel, a class automatica ...

Unique validation for matching passwords in Angular applications

Looking to incorporate a registration form into my angular/ionic app. The form consists of 6 fields within a formGroup (username, first name, last name, password, confirm password, gender). I am seeking to validate the data on the client side using Angular ...

Issue with triggering angular function multiple times in certain conditions

Issue: Experiencing difficulties with Angular directive as it is being called multiple times, resulting in incorrect transaction outcomes and multiple entries on the Console screen. Desired Outcome: Ensure that the function executes only once. Sample cod ...

"What is the best way to connect a md-input to the value of a md-slider

I'm in the process of developing an application using Angular 2.0/meteor, and I'm facing a challenge with binding an input to md-slider. Below is the HTML code for the component: <div class="panel-body"> <form [formGroup]="filtreFor ...

Understanding Vue.js - encountering the error message "property or method is not defined"

Recently, I've come across an issue that seems to be common among many people, but for some reason, I am unable to find a solution despite looking at similar questions. The problem arises when I use a v-for in a Vue Component and the array value cons ...

How can I use the target type (and maybe even the property type) as a type parameter within a decorator?

In the process of incorporating a deep-watch property decorator in Angular, the following usage has been implemented: @Component({ /* ... */ }) export class AppComp { @Watch( 'a.b.c', function (last, current, firstChange) { // ca ...

When using Vue 3 in my app, I discovered that all the TypeScript files are easily accessible through the browser console

I recently completed my Vue3 js app with Typescript, and I have noticed that all the Typescript files are easily accessible for anyone to view through the Sources tab of the browser console. The code is perfectly clear and readable. Is there a method to p ...

What could cause a variable to be lost in Angular?

Within my component, I am working with input data: <app-order-applications-list *ngSwitchCase="'DOCATTACH'" [applications]="block?.datasource?.value"></app-order-applications-list> The component code looks like th ...

When a child triggers a non-bubbling event, the view reference in Angular 2 structural directive is automatically cleared

Imagine we have a set of images that need to be displayed: <div *ngFor="let image of images; let i = index"> <div *appMaskImageOnError="i" #mydir> <img [src]="image" alt="" (error)="mydir.remove()"> </div> < ...

When working with an observable in an Angular Material table, the *ngIf directive may not function as expected

Attempting to utilize an Angular Material table with expandable rows, specifically to display information based on screen width reaching a particular breakpoint. Utilizing an observable isHandSetPortrait$ that is subscribed to in the HTML to determine if t ...