ค้นหาเว็บไซต์

typescript - Angular 4 - .filter ไม่ใช่ฟังก์ชัน


ฉันมีโค้ดนี้:

 transform(searchData: Array<vw_WebSiteCourseSearch>, searchResultContentType: string) {
        if (searchData == undefined) {
            return;
        }

        return searchData.filter((item) => item.ContentType == searchResultContentType);
    }

คอนโซลของฉันพิมพ์ว่า:

ERROR TypeError: searchData.filter is not a function
at FilterCountPipe.webpackJsonp.../../../../../src/app/Common/pipes/filterCount.pipe.ts.FilterCountPipe.transform (filterCount.pipe.ts:19)

ฉันลองเพิ่มการนำเข้าจาก rxjs/add/operator/filter แล้ว แต่ก็ยังไม่สามารถแก้ปัญหาได้ คุณมีไอเดียหรือวิธีแก้ไขไหม?

ขอบคุณ

คำตอบ #1

หาก searchData เป็นค่า null (หรือ undefined) คุณจะได้รับข้อผิดพลาดเหมือน

TypeError: cannot read property filter of null  // or undefined

เหมือนที่ @OscarPaz คิด, filter is not a function ถูกโยนออกมาเพราะ searchData ที่ได้รับไม่ใช่อาร์เรย์ (แต่ยังถูกกำหนดค่าและไม่เป็น null)

คำตอบ #2

เพียงแค่เปลี่ยน Array เป็น array ตัวแรกเป็นอ็อบเจ็กต์และตัวที่สองเป็นอาเรย์ คุณสามารถหาข้อมูลเพิ่มเติมเกี่ยวกับ ``filter` ได้ที่นี่ [1].

[1] : https://alligator.io/js/filter-array-method/

บทความที่เกี่ยวข้อง