1

Application

A simple Search bar and a button where user enters a keyword and the response returned is from a RESTful server (HTTP GET requests)

simplesearch.ts

export class SimpleSearch {
    kw: string; // keyword
    resp: string; // response from Server
}

simplesearch.service.ts

Has a simple method called searchData which does a HTTP GET request with the user's keyword as a query search. (Code not included for brevity)

simplesearch.component.ts

/*All respective headers and @Component removed from brevity*/
const OUTPUT: SimpleSearch[] = []; // create an array for storing Objects

export class SimpleSearchComponent {
    Output = OUTPUT; // define variable for array
    constructor(private httpServ: SimpleSearchService, private temp: SimpleSearch) {}

/*Search button on HTML file does this*/
Search(inputVal: string) {
    this.temp.kw = inputVal; // store the value of user's input
    this.httpServ.searchData(inputVal)
          .then(res => this.temp.resp = res); // store the response in temp.resp

    // push the Object on the Output Array
    this.Output.push({kw: this.temp.kw, resp: this.temp.resp}); 
    }
}

Interpolation Variable

I use Output as an Interpolation Variable for my HTML template. I show the data in an unordered list

<ul>
     <li *ngFor="let keyword of Output">
         <span>{{keyword.kw}}</span>
     </li>
</ul>

 Response:
 <ul>
     <li *ngFor="let answer of Output">
        <span>{{answer.resp}}</span> <!-- WHAT TO DO HERE for Array Index-->
     </li>
 </ul>

Result

I can see the keywords in a list every time a user inputs new keywords but the responses in the wrong way

How do I pass Indexing with the Interpolation? Or am I thinking wrong?

The easy way out was to create two separate Array<String> for keywords and responses and this works great since I can use the index to delete the contents on the page too but with an Object in an Array I am confused with the key: value representation and the index of the Array (OUTPUT) itself.

Community
  • 1
  • 1
Shan-Desai
  • 3,101
  • 3
  • 46
  • 89
  • 1
    I'm not sure if I understood your question.. however for this statement: *"How do I pass Indexing with the Interpolation? Or am I thinking wrong?"* You can simply do this: `
  • Index: {{i}}`.
  • – developer033 Jun 09 '17 at 20:02
  • @developer033 I get a delay of one response in the last list. Can I do something like {{answer[i].resp}} in my loop? – Shan-Desai Jun 09 '17 at 20:10
  • What do you mean by "last list"? I just can see you iterating the same list 2 times... Also I just found a problem in your code.. you're trying to access `this.temp.resp` outside the *async* function (so it's probably undefined). – developer033 Jun 09 '17 at 20:15
  • The one under `Response` I start with an empty bullet point and when I query again the older response is displayed not the new one. – Shan-Desai Jun 09 '17 at 20:20