How to communicate in Angular 4 app with the DOM?

2019-09-23 00:32发布

问题:

This question is an exact duplicate of:

  • How to access Angular 4 method from DOM? [duplicate] 1 answer

I'm try to invoke addItems method however, I'm an getting error:

Uncaught TypeError: this.addItems is not a function

I'm using Angular 4 with jQuery and fullpage.js library.

page-content.component.ts

import { Component, OnInit } from '@angular/core';
import { MyDataService } from './my-data.service';
import * as $ from 'jquery';
import 'fullpage.js';

@Component({
  selector: 'page-content',
  providers: [MyDataService],
  templateUrl: './page-content.component.html',
  styleUrls: ['./page-content.component.css']
})
export class PageContentComponent implements OnInit {
  single_post = ''; 
  posts = [];
  constructor(private newService: MyDataService) {
      this.addItems(0, this.no_of_post);
  }
  ngOnInit() {
      $(document).ready(function() {
         if($('html').hasClass('fp-enabled')){
                $.fn.fullpage.destroy('all');
            }
        $('#fullpage').fullpage({ 
            onLeave: function(index, nextIndex, direction){
              const start = this.no_of_post;
              this.no_of_post += 1;
              this.addItems(start, this.no_of_post);
            }
        });
      });
  }

  addItems(startIndex, endIndex) {
    for (let i = startIndex; i < this.no_of_post; ++i) {
        this.newService.fetchData().subscribe(data=>{
           this.single_post = data[i];
           this.posts.push(this.single_post);
        }); 
    }
  }
}

回答1:

I'd suggest you to move this call from constructor to ngOnInit()

 constructor(private newService: MyDataService) {
  this.addItems(0, this.no_of_post);
 }

And thing is that this points on its class. You don't have property no_of_post in that class.

Also you have issue with this string

onLeave: function(index, nextIndex, direction) {

Use arrow function

onLeave: (index, nextIndex, direction) => {