我试图通过这个小例子来理解 angular bei 的一些特性。
从<input type="file">
用户那里选择一个图像文件。然后 HttpClient 向后端(nodejs)发送发布请求,以将选定的图像文件保存到src/assets/images
我的 Angular 5 Web 应用程序中的文件夹中。到目前为止,一切都完美无缺。
我的实验
我想在该输入字段下方显示导入的图像。div
问题
我明白了
尽管如此,还是通过后端IMG2.jpg
成功添加了。src/assets/images
我的问题
- 如何强制
ng serve
感知应用于 angular-app 文件结构的后端更改? - 使用这样的标记是一个好习惯
<img [src]="img.path"> <!-- my variable in component.ts -->
吗?
我正在使用 angular5、angular-cli: 1.5.4、typescript ~2.4.2、OSX 10.13.2、node 8.9.1、npm 5.5.1。
先感谢您。
如果您有兴趣查看我的代码
组件.ts:
import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'screenshot',
templateUrl: './screenshot.component.html',
styleUrls: ['./screenshot.component.css']
})
export class ScreenshotComponent implements OnInit {
@Input('images') images: any[] = [];
fileInput: HTMLInputElement;
ngOnInit() {
}
// the magic was brought to you from
https://gist.github.com/aitoribanez/8b2d38601f6916139f5754aae5bcc15f
filesToUpload: any[] = [];
constructor(private http: HttpClient) { }
/**
* this will be called, wenn the button "Einfuegen" is clicked!
*/
upload(form: HTMLFormElement) {
const formData: any = new FormData();
const files: Array<any> = this.filesToUpload;
formData.append("uploads", files[0], files[0]['name']);
console.log(formData);
this.http.post('http://localhost:3001/upload', formData)
.subscribe(files => {
console.log('files', files)
this.images.push({
name: files[0].filename,
path: "assets/images/" + files[0].filename
});
console.log("images list", this.images);
})
// To reset the input field
this.fileInput.value = "";
}
fileChangeEvent(event: any) {
this.filesToUpload = event.srcElement.files;
console.log(this.filesToUpload);
this.fileInput = event.srcElement;
}
}
组件.html
<div>
<input type="file" accept=".png, .jpg, .jpeg" (change)="fileChangeEvent($event)">
<button type="submit">Eingfuegen!</button>
<div [(ngModel)]="images" *ngIf="images.length > 0" name="displayImages" ngDefaultControl>
<div class="myphoto" *ngFor="let img of images">
<img [src]="img.path" alt="{{img.name}}">
</div>
</div>
</div>