使用XMLHttpRequest发表文章时,Angular2正在刷新页面 [英] Angular2 is refreshing the page when doing a post with XMLHttpRequest
问题描述
我遇到的问题是,当我尝试使用XMLHttpRequest上传图片时,页面会刷新(并且服务成功)
I'm having this issue that when I try to upload a picture using XMLHttpRequest the page is refreshed (and the service is successfull)
这是我发布图片的功能:
This is my function to post the image:
upload(url : string, file : File) : Observable<any> {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
formData.append("file", file);
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', this.serverService.getURL() + url, true);
xhr.setRequestHeader("Authorization", 'Bearer ' + this.sessionService.getToken());
xhr.send(formData);
});
}
这是我的HTML:
<div class="panel">
<div class="panel-body">
<h4 class="page-header mt0">Select files</h4>
<div *ngIf="progress == 0" ng2FileDrop [ngClass]="{'nv-file-over': hasBaseDropZoneOver}" (onFileDrop)="onFileDrop($event)" (filDrop)="fileDropBase($event)" (fileOver)="fileOverBase($event)" [uploader]="uploader" class="box-placeholder my-drop-zone">
<label for="file2" class="file-upload">
<button type="button" class="btn btn-default btn-block file-button">Single</button>
<input id="file2" type="file" ng2FileSelect [uploader]="uploader" (change)="fileSelected()"/>
</label>
</div>
<progressbar *ngIf="progress > 0" class="progress-striped active file-upload" value="{{progress}}" type="danger"><i>{{progress}}%</i></progressbar>
</div>
</div>
这是我的组件:
export class ImageUploaderComponent implements OnInit {
progress : number = 0;
@Input()
url: string;
@Output()
fileUploaded= new EventEmitter();
public uploader: FileUploader = new FileUploader({ url: this.url });
public hasBaseDropZoneOver: boolean = false;
public fileOverBase(e: any): void {
this.hasBaseDropZoneOver = e;
}
public onFileDrop(file: any): void {
if(file.length > 0)
this.imageUploaderService.upload(this.url, file[0]).subscribe((response) => {
this.fileUploaded.emit({ code : response.data.code, logo : response.data.logo });
});
}
public fileSelected(): void {
if(this.uploader.queue.length > 0)
this.imageUploaderService.upload(this.url, this.uploader.queue[0]._file).subscribe(() => {
console.log('sent');
});
}
constructor(private imageUploaderService : ImageUploaderService) {
this.imageUploaderService.progress$.subscribe(
data => {
console.log('progress = '+data);
this.progress = data;
});
}
ngOnInit() {
}
}
有什么我想念的吗?关于此问题的帖子的大部分谈论的是在按钮中使用Type = button,但是我有这个权利.
Is there anything I'm missing? MOst of the post about this issue talk about having Type=button in the buttons , but I have that right.
我意识到的是,webpack在提交后正在重建应用程序.因此,我不知道这是否正在产生代码更改,或者是否会使Webpack认为该应用程序需要重建.希望有帮助,我迷失了这个问题.
Something I realized is that webpack is rebuilding the app after the submit. So I don't know if that is producing a code change or something that can make webpack think that the app needs a rebuild. Hope this help, I'm lost with this issue.
后端信息:Java控制器
Backend Information: Java controller
@Controller
@CrossOrigin(origins = {"http://localhost:4200", "http://clouderp.com:3000"})
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/save", method = RequestMethod.POST, consumes = "multipart/form-data")
public @ResponseBody
Response save(@RequestParam("file") MultipartFile file,
MultipartHttpServletRequest request) {
Response response = new Response();
try {
response = userService.profileImage(file, JWTTokenAuthFilter.getUsername(request));
} catch (Exception e) {
e.printStackTrace();
response.setCode(CodeList.EXCEPTION);
response.setSuccess(false);
}
return response;
}
}
我仍然在这里被封锁了几天...知道吗?
I'm still blocked here for several days... Any idea?
推荐答案
我也有类似情况.请检查您上传的位置在Angular2项目中.由于webpack-dev-server将检测到任何文件更改并重新编译.这将导致页面刷新.我在一台机器上同时开发了Frontend和Backend.我上传了文件并将其存储到Angular2资产路径中.这会导致页面自动刷新.我不确定您的情况是否与我相同,但我希望它可以帮助其他情况相同的人.
I have similar situation. Please check the location you uploaded is inside the Angular2 project. Since the webpack-dev-server will detect any file changed and re-compile it. It will cause the page refresh. I developed both Frontend and Backend in one machine. I uploaded the file and stored it into the Angular2 assets path. That cause the page refresh automatically. I am not sure your case is same as me, but I hope it can help others with same situation.
这篇关于使用XMLHttpRequest发表文章时,Angular2正在刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!