Skip to content

Instantly share code, notes, and snippets.

@LordJohn42
Created September 26, 2019 12:12
Show Gist options
  • Save LordJohn42/e5c6241d7f64712c4bc71cf747d78329 to your computer and use it in GitHub Desktop.
Save LordJohn42/e5c6241d7f64712c4bc71cf747d78329 to your computer and use it in GitHub Desktop.
Angular code examples. Code show factory for uploading 3d models. Work with Observable & Protobuf.
├── components
│   ├── model-list
│   │   ├── model-list.component.html
│   │   ├── model-list.component.scss
│   │   ├── model-list.component.spec.ts
│   │   └── model-list.component.ts
│   ├── models3d-layout
│   │   ├── models3d-layout.component.spec.ts
│   │   └── models3d-layout.component.ts
│   └── upload-model
│   ├── upload-model.component.html
│   ├── upload-model.component.scss
│   ├── upload-model.component.spec.ts
│   └── upload-model.component.ts
├── factories
│   └── models3d.factory.ts
├── forms
│   └── upload-model.form.ts
├── models3d-routing.module.ts
├── models3d.module.ts
└── services
├── integrator.service.spec.ts
└── integrator.service.ts
import { Injectable } from '@angular/core';
import { ModelRegistryServiceClient } from '../../@proto/integrator_pb_service';
import { TokenService } from '../../auth/services/token.service';
import { Observable, Observer } from 'rxjs/Rx';
import { EmptyReply, EmptyRequest, Model3d } from '../../@proto/base_types_pb';
import { grpc } from '@improbable-eng/grpc-web';
import { publishLast, refCount } from 'rxjs/internal/operators';
import { GetModelsListReply } from '../../@proto/integrator_pb';
@Injectable({
providedIn: 'root'
})
export class IntegratorService {
constructor(private client: ModelRegistryServiceClient, private tokenService: TokenService) { }
uploadModel(data: object): Observable<void> {
const req = new Model3d();
req.setId(data['id']);
req.setUrl(data['url']);
req.setPreviewUrl(data['previewUrl']);
req.setName(data['name']);
req.setCategoryName(data['categoryName']);
const md = new grpc.Metadata();
md.append('token', this.tokenService.getSync());
return Observable.create((obs: Observer<number>) => {
this.client.uploadModel(req, md, (err, response: EmptyReply) => {
console.log('in obs');
if (err) {
console.log(req);
console.log('ERROR:', 'err:', err.message, 'code:', err.code, 'md:', err.metadata);
obs.error(new Error(err.message));
} else {
obs.next(null);
obs.complete();
}
});
}).pipe(
publishLast(),
refCount()
);
}
getModelsList(): Observable<object[]> {
const req = new EmptyRequest();
const md = new grpc.Metadata();
md.append('token', this.tokenService.getSync());
return Observable.create((obs: Observer<object[]>) => {
this.client.getModelsList(req, md, (err, response: GetModelsListReply) => {
console.log('in obs');
if (err) {
console.log(req);
console.log('ERROR:', 'err:', err.message, 'code:', err.code, 'md:', err.metadata);
obs.error(new Error(err.message));
} else {
obs.next(response.getModelsList().map(item => item.toObject()));
obs.complete();
}
});
}).pipe(
publishLast(),
refCount()
);
}
}
import { environment } from '../../../environments/environment';
import { ModelRegistryServiceClient } from '../../@proto/integrator_pb_service';
export const ModelRegistryServiceClientFactory = () => {
return new ModelRegistryServiceClient(environment.proxyGrpcUrl, null);
}
<div class="row">
<div class="col-md-6">
<nb-card>
<nb-card-header>UploadModel</nb-card-header>
<nb-card-body>
<form [formGroup]="form.form" (ngSubmit)="submit()">
<div class="form-group row">
<label for="inputId" class="label col-sm-3 col-form-label">Id</label>
<div class="col-sm-9">
<input formControlName="id" type="text" nbInput fullWidth id="inputId" placeholder="Id">
</div>
</div>
<div class="form-group row">
<label for="inputName" class="label col-sm-3 col-form-label">Name</label>
<div class="col-sm-9">
<input formControlName="name" type="text" nbInput fullWidth id="inputName" placeholder="Name">
</div>
</div>
<div class="form-group row">
<label for="inputCategoryName" class="label col-sm-3 col-form-label">Category name</label>
<div class="col-sm-9">
<input formControlName="categoryName" type="text" nbInput fullWidth id="inputCategoryName" placeholder="Category name">
</div>
</div>
<div class="form-group row">
<label for="inputModel" class="label col-sm-3 col-form-label">MODEL</label>
<div class="col-sm-9">
<input type="file" nbInput fullWidth (input)="onFileInput($event, form.form.controls.url)" id="inputModel" placeholder="model">
<ng-container *ngIf="!form.form.value.url">File not loaded</ng-container>
<a *ngIf="form.form.value.url" href="{{form.form.value.url}}">{{form.form.value.url}}</a>
</div>
</div>
<div class="form-group row">
<label for="inputPreview" class="label col-sm-3 col-form-label">Preview</label>
<div class="col-sm-9">
<input type="file" nbInput fullWidth (input)="onFileInput($event, form.form.controls.previewUrl)" id="inputPreview" placeholder="preview">
<ng-container *ngIf="!form.form.value.previewUrl">File not loaded</ng-container>
<a *ngIf="form.form.value.previewUrl" href="{{form.form.value.previewUrl}}">{{form.form.value.previewUrl}}</a>
</div>
</div>
<div class="form-group row">
<div class="offset-sm-3 col-sm-9">
<button nbButton status="primary">UPLOAD</button>
</div>
</div>
</form>
</nb-card-body>
</nb-card>
</div>
</div>
import { Component, OnInit } from '@angular/core';
import { UploadModelForm } from '../../forms/upload-model.form';
import { HttpClient, HttpEventType, HttpHeaders, HttpRequest, HttpResponse } from '@angular/common/http';
import { TokenService } from '../../../auth/services/token.service';
import { Router } from '@angular/router';
import { environment } from '../../../../environments/environment';
@Component({
selector: 'upload-model',
templateUrl: './upload-model.component.html',
styleUrls: ['./upload-model.component.scss']
})
export class UploadModelComponent implements OnInit {
constructor(public form: UploadModelForm,
private http: HttpClient,
private tokenService: TokenService,
private router: Router) { }
ngOnInit() {
}
onFileInput(e, formControl) {
const file = e.target.files[0];
const formData = new FormData();
formData.append('file', file);
const headers = new HttpHeaders();
headers.append('x-arm-upload-bucket', 'wall');
console.log(headers);
const uploadReq = new HttpRequest('POST', `${environment.s3ServerUpload}/upload_front`, formData, {
reportProgress: true,
headers: new HttpHeaders({
'x-arm-upload-bucket': 'wall',
'x-arm-token': this.tokenService.getSync(),
}),
});
this.http.request(uploadReq).subscribe(event => {
if (event.type === HttpEventType.UploadProgress) {
console.log(Math.round(100 * event.loaded / event.total));
} else if (event instanceof HttpResponse) {
formControl.setValue(event.body['file_url']);
}
});
}
submit() {
this.form.submit().subscribe(
result => {
this.router.navigate([`/`]);
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment