我目前正在Angular 2中開發一種允許用戶更新他的個人資料:電子郵件和密碼的表單。Angular 2 - 帶輸入文件的模型驅動表單(文件上傳)
用戶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>
用戶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);
}
});
}
}
今天,我想通過簡單地添加文件類型字段允許上傳照片。
但我發現關於這個問題的信息很少。
唯一的解決辦法似乎接近我想要做的是在這裏: https://www.thepolyglotdeveloper.com/2016/02/upload-files-to-node-js-using-angular-2/
是否有更好的解決方案,以實現這一目標?一個更接近我的代碼的解決方案,因爲我想要最大化的標準化?例如,我已經使用$ http Angular服務了嗎?
謝謝!
答案是確切類似於[本答案](http://stackoverflow.com/a/35985489/2435473)(decto每個單詞都是複製粘貼的),爲什麼你不把它標記爲重複..而不是重新編寫它 –
是的,因爲我認爲問題是不同於那個問題,所以張貼爲答案。 –
那麼爲什麼不把它標記爲重複,如果你認爲它如此..或只是添加一個答案鏈接評論.. –