Autodesk Forge Viewer and Angular2

I’ve been using the Autodesk Forge viewer quite a bit lately to integrate 3D building models within various prototype applications. Until now I had only used the Forge Viewer with plain JavaScript (or a bit of JQuery). I recently tried to integrate the viewer within an Angular 2 application and thought I’d share my solution – as I was unable to find any examples when I did a quick google.

Angular2 (just called Angular) is a rewrite of AngularJS framework. A key difference is that Angular2 moves away from the MVC pattern in favour of Components and the shadow DOM. Although not a requirements, Angular2 recommends the use of TypeScript to help more strongly type JavaScript with a view to help maintainability of large applications. Angular is just JavaScript, so it’s not difficult to integrate external JavaScript libraries with it – you just have to follow particular conventions to get these libraries to work. The solution to integrating the Forge Viewer is very similar to some of the React samples on GitHub.

Step 1

After creating a new Angular app via angular-cli, add the required JS includes to index.html:

<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/three.min.js?v=v2.13"></script>
<script src="https://developer.api.autodesk.com/viewingservice/v1/viewers/viewer3D.min.js?v=v2.13"></script>

Note that I’m going to use the headless Forge Viewer in this example – so I don’t need to include the Forge Viewer’s CSS.

Step 2

Create a new component using angular-cli:

ng generate component forge-viewer

Add the following to forge-viewer.component.html:

<div #viewerContainer class="viewer">
</div>

This provides a Div for the Forge Viewer to render in to. We need to add a #viewerContainer reference within theDiv so that we can obtain an ElementRef to give the Forge Viewer the DOM element to bind to. Add the following CSS to forge-viewer.component.css:

.viewer {
  position: relative;
  width: 100%;
  height: 450px;
}

Step 3

We’ve done the basic setup, we now need to add the main functionality to forge-viewer.component.ts.

import { Component, ViewChild, OnInit, OnDestroy, ElementRef } from '@angular/core';

// We need to tell TypeScript that Autodesk exists as a variables/object somewhere globally
declare const Autodesk: any;

@Component({
  selector: 'forge-viewer',
  templateUrl: './forge-viewer.component.html',
  styleUrls: ['./forge-viewer.component.scss'],
})
export class ForgeViewerComponent implements OnInit, OnDestroy{
  @ViewChild('viewerContainer') viewerContainer: any;
  private viewer: any;

  constructor(private elementRef: ElementRef) { }

...

There are a couple of lines above that are crucially important. We’ve imported the Autodesk Viewer from Autodesk’s servers – this creates a global Autodesk object. We don’t have any TypeScript typings for this object (ts.d files). At time of writing, there were no definitions on the DefinatelyTyped repository. TypeScript is just a superset of JavaScript, so it’s not a problem that we don’t have a typings file. All we need to do is declare an Autodesk variable:

declare const Autodesk: any;

This tells the TypeScript compiler that somewhere globally there is an object called Autodesk.

Also important is a reference to the Div we want to render the viewer in:

@ViewChild('viewerContainer') viewerContainer: any;

Step 4

We’ll now create an instance of the Forge Viewer – we’ll need to do this once the component has been initialised AND our hosting Div has been rendered in the DOM. We’ll use the ngAfterViewInit lifecycle hook:

ngAfterViewInit() {
  this.launchViewer();
}

private getAccessToken(onSuccess: any) {
  const { access_token, expires_in } = // Your code to get a token
  onSuccess(access_token, expires_in);
}

private launchViewer() {
  if (this.viewer) {
    // Viewer has already been initialised
    return;
  }

  const options = {
    env: 'AutodeskProduction',
    getAccessToken: (onSuccess) => { this.getAccessToken(onSuccess) },
  };

  // For a headless viewer
  this.viewer = new Autodesk.Viewing.Viewer3D(this.viewerContainer.nativeElement, {});
  // For a viewer with UI
  // this.viewer = new Autodesk.Viewing.Private.GuiViewer3D(this.viewerContainer.nativeElement, {});

  Autodesk.Viewing.Initializer(options, () => {
    // Initialise the viewer and load a document
    this.viewer.initialize();
    this.loadDocument();
  });
}

private loadDocument() {
  const urn = `urn:${//document urn}`;

  Autodesk.Viewing.Document.load(urn, (doc) => {
    // Get views that can be displayed in the viewer
    const geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {type: 'geometry'}, true);

    if (geometryItems.length === 0) {
      return;
    }

    // Example of adding event listeners
    this.viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, this.geometryLoaded);
    this.viewer.addEventListener(Autodesk.Viewing.SELECTION_CHANGED_EVENT, (event) => this.selectionChanged(event));

    // Load view in to the viewer
    this.viewer.load(doc.getViewablePath(geometryItems[0]));
  }, errorMsg => console.error);
}

private geometryLoaded(event: any) {
  const viewer = event.target;

  viewer.removeEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, this.geometryLoaded);

  // Example - set light preset and fit model to view
  viewer.setLightPreset(8);
  viewer.fitToView();
}

private selectionChanged(event: any) {
  const model = event.model;
  const dbIds = event.dbIdArray;

  // Get properties of object
  this.viewer.getProperties(dbIds[0], (props) => {
    // Do something with properties.
  });
}

ngOnDestroy() {
  // Clean up the viewer when the component is destroyed
  if (this.viewer && this.viewer.running) {
    this.viewer.removeEventListener(Autodesk.Viewing.SELECTION_CHANGED_EVENT, this.selectionChanged);
    this.viewer.tearDown();
    this.viewer.finish();
    this.viewer = null;
  }
}

A lot of the code is very similar to how you’d instantiate the viewer via plain JavaScript. The following line creates a new instance of the viewer in the Div of our component template:

this.viewer = new Autodesk.Viewing.Viewer3D(this.viewerContainer.nativeElement, {});

The reset of the code just loads a document and demonstrates how events can be bound.

Gotchas

Whilst working on this prototype, I encountered one gotcha. I could successfully create an instance of the Viewer and load a model in to it. My application had simple routing – when I navigated away from the route where the viewer was hosts, to another route and then back, the viewer wouldn’t display. It seemed that viewer thought it has already been instantiated so didn’t bother and skipped to loading the model…which didn’t work because there was no instance of the viewer.

My solution to the problem isn’t as elegant as I wanted, but does work:

this.viewer = new Autodesk.Viewing.Viewer3D(this.viewerContainer.nativeElement, {}); // Headless viewer

// Check if the viewer has already been initialised - this isn't the nicest, but we've set the env in our
// options above so we at least know that it was us who did this!
if (!Autodesk.Viewing.Private.env) {
  Autodesk.Viewing.Initializer(options, () => {
    this.viewer.initialize();
      this.loadDocument();
  });
} else {
  // We need to give an initialised viewing application a tick to allow the DOM element to be established before we re-draw
  setTimeout(() => {
    this.viewer.initialize();
    this.loadDocument();
  });
}

The 2nd time out component loads, Autodesk.Viewing.Private.env will already be set (we set it!). So we simply call initialise on the viewer and load the model. This didn’t work first time – but adding a setTimeout gave Angular a tick to sort out DOM binding/it’s update cycle before attempting to load the viewer.

Screenshots

The full forge-viewer.component.ts file

import { Component, ViewChild, OnInit, OnDestroy, ElementRef, Input } from '@angular/core';

// We need to tell TypeScript that Autodesk exists as a variables/object somewhere globally
declare const Autodesk: any;

@Component({
  selector: 'forge-viewer',
  templateUrl: './forge-viewer.component.html',
  styleUrls: ['./forge-viewer.component.scss'],
})
export class ForgeViewerComponent implements OnInit, OnDestroy {
  private selectedSection: any = null;
  @ViewChild('viewerContainer') viewerContainer: any;
  private viewer: any;

  constructor(private elementRef: ElementRef) { }

  ngOnInit() {
  }

  ngAfterViewInit() { 
    this.launchViewer();
  }

  ngOnDestroy() {
    if (this.viewer && this.viewer.running) {
      this.viewer.removeEventListener(Autodesk.Viewing.SELECTION_CHANGED_EVENT, this.selectionChanged);
      this.viewer.tearDown();
      this.viewer.finish();
      this.viewer = null;
    }
  }

  private launchViewer() {
    if (this.viewer) {
      return;
    }

    const options = {
      env: 'AutodeskProduction',
      getAccessToken: (onSuccess) => { this.getAccessToken(onSuccess) },
    };

    this.viewer = new Autodesk.Viewing.Viewer3D(this.viewerContainer.nativeElement, {}); // Headless viewer
 
    // Check if the viewer has already been initialised - this isn't the nicest, but we've set the env in our
    // options above so we at least know that it was us who did this!
    if (!Autodesk.Viewing.Private.env) {
      Autodesk.Viewing.Initializer(options, () => {
        this.viewer.initialize();
        this.loadDocument();
      });
    } else {
      // We need to give an initialised viewing application a tick to allow the DOM element to be established before we re-draw
      setTimeout(() => {
        this.viewer.initialize();
        this.loadDocument();
      });
    }
  }

  private loadDocument() {
    const urn = `urn:${// model urn}`;

    Autodesk.Viewing.Document.load(urn, (doc) => {
      const geometryItems = Autodesk.Viewing.Document.getSubItemsWithProperties(doc.getRootItem(), {type: 'geometry'}, true);

      if (geometryItems.length === 0) {
        return;
      }

      this.viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, this.geometryLoaded);
      this.viewer.addEventListener(Autodesk.Viewing.SELECTION_CHANGED_EVENT, (event) => this.selectionChanged(event));

      this.viewer.load(doc.getViewablePath(geometryItems[0]));
    }, errorMsg => console.error);
  }

  private geometryLoaded(event: any) {
    const viewer = event.target;

    viewer.removeEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, this.geometryLoaded);
    viewer.setLightPreset(8);
    viewer.fitToView();
    // viewer.setQualityLevel(false, true); // Getting rid of Ambientshadows to false to avoid blackscreen problem in Viewer.
  }

  private selectionChanged(event: any) {
    const model = event.model;
    const dbIds = event.dbIdArray;

    // Get properties of object
    this.viewer.getProperties(dbIds[0], (props) => {
       // Do something with properties
    });
  }

  private getAccessToken(onSuccess: any) {
    const { access_token, expires_in } = // get token
    onSuccess(access_token, expires_in);
  }
}
Advertisements

4 thoughts on “Autodesk Forge Viewer and Angular2

  1. Ivan says:

    Hi, very cool tutorial. I’m trying to follow along, but for some reason my Angular app is not detecting the Autodesk variable inside the JavaScript files.

    ‘Error: Uncaught (in promise): ReferenceError: Autodesk is not defined.’

    I did add the ‘declare const Autodesk: any;’ in my Angular component, and the script tags on my index.html.

    Do you know what could be causing this?
    Thank you very much,
    Ivan

      • Thanks for the feedback Ivan. I think I originally wrote this sample with Angular 2 using a beta of the Angular cli. I’ll try to upgrade the sample to Angular 4 and see if I can repeat the issue you’re having.

      • Ivan says:

        Hi there. Thank you very much. Actually I did solve the issue. Going to explain how for anyone that might have the same problem:

        When using a Node + Angular 4 app, you have to add the script tags for the autodesk js files inside the HEAD tag of the html file where you load your Angular app.

        Apparently, even though the script files load fine in the body or even adding them inside your component .ts file (not the view html, script tags there get ignored by Angular), you can only access it’s contents if you put the script tags in the HEAD of the main HTML file.

        Weird, but that’s how it works, at least on my setup.

        Hope this helps someone with similar issues!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s