angular - Typescript คุณสมบัติ 'length' ไม่มีอยู่ในชนิด
ฉันเป็นมือใหม่ด้าน Typescript และกำลังพยายามให้โค้ดตัวอย่างดังต่อไปนี้ทำงานได้:
quoteService.getQuoteOfTheDay()
.then(quotes => this.quote = quotes[Math.floor(Math.random() * quotes.length)]);
แนวคิดคือการเลือกคำคมจากอาร์เรย์แบบสุ่ม
แทนที่จะเป็นเช่นนั้น ฉันกลับได้รับข้อผิดพลาดดังต่อไปนี้ใน Terminal Property 'length' does not exist on type 'Quote'.
ถ้าฉันเปลี่ยน quotes.length เป็น 4 โค้ดก็ทำงานได้ แต่ฉันต้องการให้ฟังก์ชันหาจำนวนคำคมที่มี แล้วจึงสุ่มคืนคำคมหนึ่งคำ
นี่คือส่วนประกอบทั้งหมดด้านล่าง
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)]);
}
}
ไฟล์ quote.service.ts ผิดพลาด
getQuoteOfTheDay(): Promise<Quote> {
return this.http.get('quote.json').toPromise()
.then(response => response.json());
}
ควรจะเป็นแบบนี้
getQuoteOfTheDay(): Promise<any> {
return this.http.get('quote.json').toPromise()
.then(response => response.json());
}
คำตอบ #1
ประเภทของคุณสำหรับ getQuoteOfTheDay(): Promise<Quote> ดูเหมือนจะผิด แม้ว่าชื่อวิธี ประเภทของวิธี และชื่อไฟล์ทั้งหมดจะบ่งบอกว่าคำสัญญาที่ส่งกลับจะคืนค่าเพียงคำคมเดียว แต่คอมโพเนนต์ของคุณกำลังใช้มันเหมือนกับว่ามันส่งกลับเป็นอาร์เรย์ของคำคม คุณจะต้องใช้
getQuotesOfTheDay(): Promise<[Quote]> {
// ^ ^ ^
return this.http.get('quotes.json').toPromise()
// ^
.then(response => response.json());
}
คำตอบ #2
ลองใช้ quotes[].length เนื่องจากดูเหมือนว่าจะเป็นอาร์เรย์
