【问题标题】:ERROR TypeError: Cannot read property 'setupScene' of undefined in Angular 4错误类型错误:无法读取 Angular 4 中未定义的属性“setupScene”
【发布时间】:2017-10-30 01:43:05
【问题描述】:

如何在类型脚本的 Load 函数中调用 Angular 类函数。 如何在 angular-cli.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;
  }
}

获取错误:

错误类型错误:无法读取未定义的属性“setupScene”。

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

【问题讨论】:

    标签: javascript angular three.js angular-cli


    【解决方案1】:

    this指的是init函数没有setupScene功能,你应该使用箭头函数,

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

    【讨论】:

    • 这工作正常,但 3D-json 没有渲染到画布上。
    • 什么是 3D-Json?
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-16
      • 2021-11-05
      • 1970-01-01
      • 2018-04-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-15
      • 2018-11-21
      相关资源
      最近更新 更多