无法读取属性'推送'未定义的角度2,非常不合理的错误

时间:2016-12-29 17:23:08

标签: angular

这不是一个非常具有描述性的错误。我使用数组push函数以相同的方式在我的项目中生成书籍,当我为客户做同样的事情时,我得到了上述错误。我将在下面发布一个失败的方法,我也有关于GitHub的项目HERE

ngOnInit(){

        this.bookService.getAllBooks().forEach((books) => {
            this.book = books;
            this.availableFictionBooks = this.bookService.getAvailbleFictionBooks(books);
            this.availableProgrammingBooks = this.bookService.getAvailbleProgrammingBooks(books);
            this.availableNonFictionBooks = this.bookService.getAvailbleNonFictionBooks(books);
        });

        this.customerService.allCustomers().filter(libraryCustomers => {
           this.customers = this.customerService.allCustomers()
        });

        this.bookService.getAllBooks().filter(books => {
           this.allBooks = this.bookService.getAllBooks();
        });

    }

问题是this.customerService,当我注释掉这一行时,一切正常。

的CustomerService:

   generateCustomers():void {

        let id: number = 0;

        this.generateCustomersHelper(id++,"Drew","Jocham",this.bookGenerator());
        this.generateCustomersHelper(id++,"Alex","Williams",this.bookGenerator());
        this.generateCustomersHelper(id++,"Justin","Kavanagh",this.bookGenerator());
        this.generateCustomersHelper(id++,"Mike","Johnson",this.bookGenerator());
        this.generateCustomersHelper(id++,"Kori","Costner",this.bookGenerator());

    }

    getAllCustomers(): Customer[] {

        this.generateCustomers();

        return this.customers;

    }

    generateCustomersHelper(id: number, name: string, lastName: string, booksRented?: Array<IBook>): void {

        let newCustomer = new Customer();

        newCustomer = {id, name, lastName, booksRented };

        this.customers.push(newCustomer);
    }

1 个答案:

答案 0 :(得分:0)

此错误消息实际上是完全描述性的。这就是说,在执行第this.customers.push()行时,this.customers未定义。这是因为您从不初始化变量,只需将= []添加到声明它的行即可修复,就像BookService books变量中的(function (module) { function DetailController($scope) { //long codes } module.controller('DetailController', DetailController); })(angular.module('app.main')); 一样。

相关问题