Reputation:
I'm new to Typescript and have been trying to get the following snippet to work:
quoteService.getQuoteOfTheDay()
.then(quotes => this.quote = quotes[Math.floor(Math.random() * quotes.length)]);
The idea is to randomly select a quote from the array.
Instead I get the following error in Terminal Property 'length' does not exist on type 'Quote'.
If I change quotes.length
to 4
the snippet works but I want to the function to figure out how many quotes there are and then randomly return a single one.
Here is the entire Component below.
import { Component } from '@angular/core';
import { MaterialModule } from '@angular/material';
import { Http } from '@angular/http';
import { Quote } from './quote.model';
import { QuoteService } from './quote.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [QuoteService]
})
export class AppComponent {
title = 'App is running!';
quote: Quote;
constructor(quoteService: QuoteService) {
quoteService.getQuoteOfTheDay()
.then(quotes => this.quote = quotes[Math.floor(Math.random() * quotes.length)]);
}
}
The quote.service.ts was wrong
getQuoteOfTheDay(): Promise<Quote> {
return this.http.get('quote.json').toPromise()
.then(response => response.json());
}
Should have been like this
getQuoteOfTheDay(): Promise<any> {
return this.http.get('quote.json').toPromise()
.then(response => response.json());
}
Upvotes: 3
Views: 20681
Reputation: 664307
Your type for getQuoteOfTheDay(): Promise<Quote>
seems to be wrong. While the method name, method type and file name all suggest that the returned promise will fulfill with only a single quote, your component is using it as if it returned an array of quotes. You'll want to use
getQuotesOfTheDay(): Promise<[Quote]> {
// ^ ^ ^
return this.http.get('quotes.json').toPromise()
// ^
.then(response => response.json());
}
Upvotes: 3