繁体   English   中英

错误TypeError:无法读取Angular 4中未定义的属性'setupScene'

[英]ERROR TypeError: Cannot read property 'setupScene' of undefined in Angular 4

如何在类型脚本的Load函数中调用Angular类函数。 如何在angular-cli的类型脚本中的load方法中调用method.Angular-cli返回错误的未定义函数。

import { Component, OnInit ,ElementRef, ViewChild} from '@angular/core';
import {ProjectService} from '../service/project.service';
import {ComponentService} from '../service/component.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Validations } from '../app.validations';
import {Observable} from 'rxjs/Observable';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { Configuration } from '../app.constants';
import { UtilityService } from '../shared/utility.service';
import * as THREE from 'three';


@Component({
  selector: 'app-configuration',
  templateUrl: './configuration.component.html',
  styleUrls: ['./configuration.component.css']
})
export class ConfigurationComponent implements OnInit {
  /* Three Js configuration */

  @ViewChild('container') elementRef: ElementRef;
  private container : HTMLElement;
  private scene: THREE.Scene;
  private camera: THREE.PerspectiveCamera;
  private renderer: THREE.WebGLRenderer;
  private cube : THREE.Mesh;
  objNew : any;
  /* End */
  configuration:any =[];
  component_id : string;
  project_id :string;
  constructor(public Configuration: Configuration, private project:ProjectService,private route: ActivatedRoute,
              private router: Router, private validations : Validations,private formBuilder: FormBuilder,
              private component:ComponentService,
              private _utility : UtilityService) {

    console.log(THREE);
  }
  /**
   * @methodOf initialization
   * @method : get params
   * @param : component_id
   * */
  ngOnInit() {
    this.component_id = this.route.snapshot.params["id"];
    this.project_id = localStorage.getItem('project_id');
    this.container = this.elementRef.nativeElement;
    console.log('manish');
    this.init();


    this._utility.showLoading(true);
    this.component.getConfiguration().subscribe(data => this.success(data,'componentconfiguration'),
        error => this.HandleError(error,'componentconfiguration')
    );
  }

  success(response,type) {
    if(response.status_code == 200 ){
      this._utility.showLoading(false);
      this.configuration = response;

    } else if(response.status_code == 201){
      this.router.navigate(['configuration/'+this.component_id ]);
    } else{
      alert('Something went wrong');
    }
  }
  HandleError(error,type){
    alert('Something went wrong.');
    this.router.navigate(['dashboard']);

  }

  /* init function for 3js*/
  init(){
    let screen = {
        width  : 350,
        height : 400
      },
      view = {
        angle  : 45,
        aspect : screen.width / screen.height,
        near   : 0.1,
        far    : 1000
      };

    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(view.angle, view.aspect, view. near, view.far);
    this.renderer = new THREE.WebGLRenderer();

    this.renderer.setSize(screen.width, screen.height);
    this.container.appendChild(this.renderer.domElement);
    var loader = new THREE.ObjectLoader();
    // TODO : input yout exported json file
    var url = './assets/json/scene.json';
    loader.load(url, function(obj) {
      this.setupScene(obj);
    });

    this.render();
  }
  render(){
    let self: ConfigurationComponent = this;
    (function render(){
      requestAnimationFrame(render);
      self.renderer.render(self.scene, self.camera);
      self.animate();
    }());
  }

  animate(){
    if(this.scene && this.camera) {
      this.renderer.render(this.scene, this.camera);
      this.camera.lookAt(this.scene.position);
      //this.objNew.autoRotate = true;
      // hideShow(objNew,objNew.children[0],showHide);
      //this.rotateAroundWorldAxis(this.objNew);
    }
    (function animate(){
    requestAnimationFrame(animate);
    }());

  }

  setupScene(result) {
    var scene = result;
    this.objNew = scene.children[2];
    console.log(this.objNew)
    // find main camera by tag
    this.camera = this.findByUserData(scene, "tag", "MainCamera");
    // calculate aspect. use window size.
    var winsize = this.renderer.getSize();
    this.camera.aspect = window.innerWidth/ window.innerHeight;
    this.camera.updateProjectionMatrix();

  }
  /* find data */
  findByUserData(node, key, value) {
    if(node.userData && node.userData[key] == value) {
      return node;
    }
    for(var i = 0 ; i < node.children.length ; i++) {
      var child = node.children[i];
      var found = this.findByUserData(child, key, value);
      if(found != null) {
        return found;
      }
    }
    return undefined;
  }

  rotateAroundWorldAxis(obj) {
    obj.rotation.x = obj.rotation.x;
    obj.rotation.y = 0.01 + obj.rotation.y;
    obj.rotation.z = obj.rotation.z;
  }
}

错误获取:

错误TypeError:无法读取未定义的属性'setupScene'。

请建议我如何在Angular-cli中运行3-js对象加载器。 如何解决呢?

使用箭头功能保留上下文( this关键字):

loader.load(url, obj => {
  this.setupScene(obj);
});

这是指不具有setupScene函数的init函数,应使用箭头函数,

loader.load(url, obj => {
  this.setupScene(obj);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM