Angular中如何存储Froala编辑器上传至S3的图片链接
Hey there! I see the issue you're running into—when you try to assign this.imageLink = link inside the Froala image.uploadedToS3 event, the this keyword isn't pointing to your Angular component instance (it's pointing to the Froala editor instance instead). That's why your variable isn't getting updated.
Here's how to fix it with two straightforward approaches, with the first being the most clean and Angular-friendly:
1. Use an Arrow Function for the Event Callback
Arrow functions inherit the this context from their surrounding scope (your component), so you'll be able to access this.imageLink correctly. Update your options object like this:
export class WriterComponent implements OnInit { imageLink: string; public options: Object = { heightMin: 300, events: { 'froalaEditor.image.uploadedToS3': (e, editor, link, key, response) => { // Now "this" refers to your WriterComponent instance this.imageLink = link; console.log('Successfully saved image link:', this.imageLink); // Verify the value } // Add other events here... } }; constructor(private _usersService: UsersService) { } ngOnInit() { this._usersService.getS3Hash().subscribe(resp => { this.options['imageUploadToS3'] = resp; }); } }
2. (Alternative) Bind the Component Context to the Callback
If you prefer using a regular function, you can explicitly bind your component's this to the callback. You can do this in your ngOnInit method:
export class WriterComponent implements OnInit { imageLink: string; public options: Object = { heightMin: 300, events: {} }; constructor(private _usersService: UsersService) { } ngOnInit() { this._usersService.getS3Hash().subscribe(resp => { this.options['imageUploadToS3'] = resp; }); // Bind component context to the event callback this.options.events['froalaEditor.image.uploadedToS3'] = function(e, editor, link, key, response) { this.imageLink = link; }.bind(this); } }
Why This Works
- In regular function callbacks (like your original code),
thisis determined by how the function is called—Froala calls it with the editor instance asthis. - Arrow functions don't have their own
this; they use thethisvalue from the enclosing lexical scope (your component), which is exactly what we need to updateimageLink.
You can test if this works by adding {{ imageLink }} in your component's template, or checking the console log we added—you should see the S3 image link printed there after uploading an image.
内容的提问来源于stack exchange,提问作者sachin patidar

