How to send a variable to a different function in Angular 2 using Firebase?

In my code, there is a function that works with firebase storage to generate download URLs for uploaded files. Here's an example of the function:

 uploadHandler(upload: Project) {
    const storageRef = firebase.storage().ref();
    const uploadTask = storageRef.child(`${this.basePath}/${upload.file.name}`).put(upload.file);

    uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
      (snapshot: firebase.storage.UploadTaskSnapshot) =>  {
        // handle upload progress
        const snap = snapshot;
        upload.progress = (snap.bytesTransferred / snap.totalBytes) * 100;
      },
      (error) => {
        // handle upload failure
        console.log(error);
      },
      () => {
        // handle upload success
        if (uploadTask.snapshot.downloadURL) {
          upload.url = uploadTask.snapshot.downloadURL; // this is the URL variable
          upload.name = upload.file.name;

          this.fire.collection(`users/${this.auth.userId}/projects`).add( { photoURL: upload.url, file: upload.file.name, })
          this.saveFileData(upload);
          return;
        } else {
          console.error('No download URL found!');
        }
      },
    );
  }

Now, I would like to utilize the generated URL in another function where I have a parameter urlPath:string:

 public accessZipFileContent(urlPath:string, pathInZip:string) {
    getFileContentFromRemoteZip(urlPath, pathInZip, (content) => {
      console.log(content);
    });
  }
}

How can I achieve this?

Answer №1

One way to execute your function is by directly calling it from the complete part of your request like this:

() => {
    // Handle upload success
    if (uploadTask.snapshot.downloadURL) {
      upload.url = uploadTask.snapshot.downloadURL;
      upload.name = upload.file.name;

      this.fire.collection(`users/${this.auth.userId}/projects`).add( { 
      photoURL: upload.url, file: upload.file.name, })
      this.saveFileData(upload);
      this.getZipFileContent(upload.url, path);
      return;
    } else {
      console.error('No download URL!');
    }

Another approach is to assign the download URL to a local variable and then use the function without that parameter:

this.urlPath= uploadTask.snapshot.downloadURL;

And then call the function like this:

public getZipFileContent(pathInZip:string) {
getFileContentFromRemoteZip(this.urlPath, pathInZip, (content) => {
  console.log(content);
});

}

Answer №2

Oops, I may have been too quick to solve it on my own :D

When needing to utilize a variable that is not within the current function scope, one approach is to call that function within another function containing the necessary variables.

fetchData() {
    this.data = this.db.list(`user/${this.auth.userId}/info`).snapshotChanges().map((actions) => {
      return actions.map((a) => {
        const details = a.payload.val();
        this.retrieveFileContents(details.url, 'hello.html');
        const $id = a.payload.key;
        const $reference = a.payload.ref; 
        return { $id, ...details, $reference };
      });
    });
    return this.data;
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Manage input from either mouse or touch events based on the event type

I've encountered a challenge with my general handler function that processes both mouse and touch events. Despite my efforts, Typescript keeps issuing errors due to the distinction between mouseEvent and touchEvent. function handleStopDrag(e: MouseEv ...

Exploring Angular2: Implementing oauth2 with token headers

As someone who is new to Angular 2, I found that things were much simpler with interceptors in version 1.*. All you had to do was add them and suddenly your headers were available everywhere, making it easy to handle requests especially when dealing with i ...

How can I make the navbar in Angular stay fixed in place?

After using the ng generate @angular/material:material-nav --name=home command to create a navbar, I am trying to make it fixed at the top while scrolling. I attempted using position: fixed; on my mat-sidenav-content but it didn't work. Does anyone ha ...

Is there a RxJS equivalent of tap that disregards notification type?

Typically, a tap pipe is used for side effects like logging. In this scenario, the goal is simply to set the isLoading property to false. However, it's important that this action occurs regardless of whether the notification type is next or error. Thi ...

Unresolved HTTP header problem with Angular 4 and Siteminder

Struggling with integrating Siteminder authentication for my nodejs/angular 4 web application has been a challenge for me over the past few weeks. On the server side (node), my code looks like this: app.get('*', function(req, res) { //read Si ...

Access Denied: Origin not allowed

Server Error: Access to XMLHttpRequest at '' from origin 'http://localhost:4200' has been blocked by CORS policy. The 'Access-Control-Allow-Origin' header is missing on the requested resource. import { Injectable } from &apo ...

How to resolve the issue of checkbox not binding the value of an object field in Angular 4?

Can anyone help me with binding the field value in the current object and switching the checkbox based on its value? This is my checkbox: <label class="checkbox-inline checbox-switch switch-success"> <input #livingRoom type="checkbox" name ...

Tips for ensuring only one property is present in a Typescript interface

Consider the React component interface below: export interface MyInterface { name: string; isEasy?: boolean; isMedium?: boolean; isHard?: boolean; } This component must accept only one property from isEasy, isMedium, or isHard For example: <M ...

the ng-repeat directive disables input controls within the tfoot

When working with JSON data, I encountered a situation where I needed to display different types of student details in a table. For one specific type of student, namely partners, I wanted to include input controls such as checkboxes and buttons. However, e ...

Obtaining the specified cell in a row when a button is clicked

I'm currently grappling with how to retrieve the value of the nth cell in the same row as the button that was clicked in angular2. I understand that I need to pass the $event value, but I'm unsure of how to extract the relevant data. In app.comp ...

Webpack is having trouble compiling TypeScript 3.7 due to the inclusion of features such as Optional Chaining and Nullish Coales

Trying to utilize the latest features of TypeScript 3.7 such as Optional Chaining and Nullish Coalescing is causing an error in webpack during transpilation. app: Module parse failed: Unexpected token (50:40) app: File was processed with these loaders: ...

ng-select issue: list not refreshing

I am encountering an issue with the method below that updates the modules array. Even though the console displays the result correctly, the ng-select does not update the list accordingly. I attempted to use this.modules=[...elements], but it did not work ...

Display an HTML tag with JavaScript

My code is in both HTML and TS files. The content stored in the Description variable looks like this: <div>aaaa</div><div>bbbb</div><div>cccc</div> Currently, the output displays as follows: aaaabbbbcccc I want to modi ...

What causes the child component to be rendered four times when the parent component is first loaded?

I have been facing an interesting scenario with my parent and child components. Typically, change detection is triggered by events like HTTP requests or timers such as setInterval and setTimeout. However, in this particular case, I am not utilizing any of ...

Typescript's Integrated Compatibility of Types

One important concept I need to convey is that if one of these fields exists, then the other must also exist. When these two fields are peers within the same scope, it can be challenging to clearly communicate this connection. Consider the example of defi ...

Steps for importing the config ts file into another ts file in Ionic 2

When trying to import the app.config.ts file in another ts file such as /pages/home/home.ts, I have included the following code in app.config: import { OpaqueToken } from "@angular/core"; export let APP_CONFIG = new OpaqueToken("app.config"); e ...

Choose from a variety of options for color schemes and hover effects

Looking to create a selector where users can pick a color. I tried changing the background color for each option, but when hovering over them, the background turns blue - which is not what I want. Check out the pictures for clarification: https://i.sstatic ...

Tips for resolving the issue of "The types 'GameState' and 'string' do not intersect, so this condition will always yield 'false'."

I need to display different components based on the value of gameStatus: import React from "react"; import { useAppSelector } from "./hooks/redux"; import EndScreen from "./pages/EndScreen"; import QuestionsPage from "./p ...

Tips on applying border to unique marker icon in Angular2 using agm-marker

https://i.sstatic.net/HH36B.png Hello everyone, I've been working on a project and need some assistance. My goal is to dynamically add custom marker icons to specific lat/lng coordinates, each with additional values such as a "color name" for border ...

Webpack is struggling to locate core-js paths when running on Windows operating systems

When running webpack, I am encountering the following errors: ERROR in ./node_modules/core-js/index.js Module not found: Error: Can't resolve './es' in 'pathtoproject\node_modules\core-js' @ ./node_modules/core-js/index. ...