Using the service in the dialog

Now that we have a working preview service, we can use it in our dialog. In order to use it, we are going to pass it into our constructor. As the service is injectable, we can let Angular take care of injecting it for us as long as we add an appropriate reference in our constructor. At the same time, we are going to add in a reference to the dialog itself, as well as a set of declarations that will be used in the corresponding HTML template:

protected imageSource: IPictureModel | null;
protected message: any;
protected description: string;
protected tags: string;

constructor(
private dialog: MatDialogRef<FileuploadComponent>,
private preview: FilePreviewService) { }
The technique that allows Angular to automatically build up constructors with dependencies, without us having to explicitly instantiate them with new, is known as dependency injection. This fancy term simply means that we tell Angular what our class needs and leave the building of the objects for that class to Angular. In effect, we tell Angular what we need without worrying about how it will be built. The act of building the classes can lead to very complex internal hierarchies, as the dependency injection engine may have to build up classes that our code relies on as well.

With this reference in place, we are going to create a method to accept the file selection from the file upload component and call our Preview method. catch is in place to cater for our defensive coding in the service, as well as to cater for situations where the user tries to upload a non-image file. If the file is invalid, the dialog will show a message informing the user of this:

public OnImageSelected(files: any): void {
this.preview.Preview(files).then(r => {
this.imageSource = r;
}).catch(r => {
this.message = r;
});
}

The last thing we need to do with the code side of the dialog is to allow the user to close the dialog and pass the selected values back to the calling code. We update the image source description and tags with the relevant local values. The close method closes the current dialog and returns imageSource back to the calling code:

public Save(): void {
this.imageSource.Description = this.description;
this.imageSource.Tags = this.tags;
this.dialog.close(this.imageSource);
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.121.131