Reputation: 523
I am currently developing in Angular 2 a form that allows a user to update his profile: email and password.
user-edit.component.html:
<form novalidate="novalidate" [ngFormModel]="form" (ngSubmit)="form.valid && onSubmit()">
<fieldset>
<div>
<label for="email">
Email
</label>
<input id="email" type="email" #email="ngForm" ngControl="email"/>
<div class="error" *ngIf="email.control.hasError('required') && email.touched">
This value is required.
</div>
</div>
<div>
<label for="password">
Password
</label>
<input id="password" type="password" #password="ngForm" ngControl="password"/>
<div class="error" *ngIf="password.control.hasError('required') && password.touched">
This value is required.
</div>
</div>
</fieldset>
<button type="submit" [disabled]="!form.valid">
Save
</button>
</form>
user-edit.component.ts:
@Component({
selector: 'user-edit',
templateUrl: 'app/components/user-edit/user-edit.component.html',
})
export class UserEditComponent implements OnInit {
form: any;
errors = [];
constructor(
private _formBuilder: FormBuilder,
private _router: Router,
private _userService: UserService
) {}
ngOnInit() {
this.form = this._formBuilder.group({
'email': ['', Validators.required)],
'password': ['', Validators.required],
});
}
onSubmit() {
var self = this;
this._userService.edit(this.form.value, function (response: Response) {
console.log('OK');
}, function (response: Response) {
console.log('ERROR');
});
}
}
user.service.ts:
@Injectable()
export class UserService {
constructor (
private _http: Http
) {}
edit(user: User, cfOnNext?: Function, cfOnError?: Function): void {
let body = JSON.stringify(user);
let headers = new Headers({
'Content-Type': 'application/json',
});
let options = new RequestOptions({
headers: headers,
});
self._http.put('https://api.dom/me', body, options).subscribe(function (response) {
if (cfOnNext) {
cfOnNext(response);
}
}, function (response) {
if (cfOnError) {
cfOnError(response);
}
});
}
}
Today I want to allow uploading of a photo by simply adding a file type field.
But I found very little information on the subject.
The only solution seems to approach what I want to do is here: https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/
Is there a better solution to achieve this? A solution that is closer to my code because I want maximum standardization? For example with the $http Angular service I already use?
Thanks!
Upvotes: 4
Views: 5647
Reputation: 86730
File Uploading in angular2,
In fact, the Http
class doesn't support that at the moment.
You need to leverage the underlying XHR object to do that:
import {Injectable} from 'angular2/core';
import {Observable} from 'rxjs/Rx';
@Injectable()
export class UploadService {
constructor () {
this.progress$ = Observable.create(observer => {
this.progressObserver = observer
}).share();
}
private makeFileRequest (url: string, params: string[], files: File[]): Observable {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
}
See this plunkr for more details: https://plnkr.co/edit/ozZqbxIorjQW15BrDFrg?p=info.
There is a an issue and a pending PR regarding this in the Angular repo:
took answer from here
Upvotes: 2