Unreachable Angular data without using subscribe

I am facing an issue with Angular 2 (apologies for my limited English proficiency...).

I need to be able to modify a component variable from another component. The trouble is, this component variable remains undefined outside the subscribe function even though it is clearly defined within. Therefore, I am unable to access this variable without being within this specific component.

Below is my service named MailRepertoryService:

    import { Injectable } from '@angular/core';
    import { Http } from '@angular/http';
    import 'rxjs/add/operator/map';

    @Injectable()
    export class MailRepertoryService {

      constructor(private http: Http) { }

      getMailsRepertory() {
        return this.http
          .get('data/dossiers.json')
          .map(res => res.json());
      }

      getMailsRepertoryFields() {
        return this.http
          .get('data/champs.json')
          .map(res => res.json())
      }

    }

And here is my AppComponent:

    import { Component, Input } from '@angular/core';
    import { MailRepertoryService } from './services/mail.repertory.service';
    import { Box, Field, Mail } from './types/mailbox.type';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })

    export class AppComponent {

      private title = 'Em Ta Box';
      boxRepertory: Box[];
      mailRepertory: Box;
      fields: Field[];
      private errors: string;

      constructor(private mailRepertoryService: MailRepertoryService) {}

      ngOnInit() {
        this.mailRepertoryService.getMailsRepertory().subscribe(
          (mailRepertories: Box[]) => {
            this.boxRepertory = mailRepertories;
            console.log(this.boxRepertory); // object displayed correctly
          },
          error => {
            console.error(error);
            this.errors = error;
          }
        );
        this.mailRepertoryService.getMailsRepertoryFields().subscribe(
          data => this.fields = data,
          error => {
            console.error(error);
            this.errors = error;
          }
        );
        console.log(this.boxRepertory); // remains undefined
      }

    }

Is there a way for me to access the this.boxRepertory variable outside of the subscribe method?

Thank you in advance.

Answer №1

Give this a shot. Use Observable from rxjs to incorporate flatMap

ngOnInit() {
    this.mailRepertoryService.getMailsRepertory().flatMap(
      (mailRepertories: Box[]) => {
        this.boxRepertory = mailRepertories;
        console.log(this.boxRepertory); // object visible
        return this.mailRepertoryService.getMailsRepertoryFields();
 }).subscribe(
      data => this.fields = data,
      (error) => {
        console.error(error);
        this.errors = error;
      }, 
      () => {
        console.log(this.boxRepertory);
      });
   }

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

How do I designate the compiled migration location?

Currently, I am utilizing the PostgreSQL database ORM Sequelize along with TypeScript as a backend script within the Express Node.js environment. My first inquiry is: Is it possible to directly create a model in .ts format? The second question pertains t ...

What is the best method for presenting backend exceptions in Angular?

I am currently working on setting up a WebAPI in .Net6 along with Angular. For the registration page, I have made the email unique (which serves as a username credential). Now, I want to notify users when they try to register with an email that is already ...

Creating a dynamic union type in Typescript based on the same interface properties

Is it possible to create a union type from siblings of the same interface? For example: interface Foo { values: string[]; defaultValue: string; } function fooo({values, defaultValue}: Foo) {} fooo({values: ['a', 'b'], defaultVal ...

Is there a way to eliminate the line that appears during TypeScript compilation of a RequireJS module which reads: Object.defineProperty(exports, "__esModule", { value: true });?

Here is the structure of my tsconfig.json file: { "compileOnSave": true, "compilerOptions": { "module": "amd", "noImplicitAny": false, "removeComments": false, "preserveConstEnums": true, "strictNullChecks": ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Using pinia always results in undefined arrays within the state

Pinia has been a crucial part of my Vue3 projects, and I've encountered a dilemma while trying to store temporary data in Pinia. Here's a snippet from my store file: // template.ts export const useTemplateStore = defineStore('template', ...

JavaScript Looping through multiple files for upload will return the last file in the series

I'm currently working on implementing a multiple file upload feature using JavaScript. Within my HTML, I have the following input: <input type="file" (change)="fileChange($event,showFileNames)" multiple /> When the onChange event is triggere ...

The issue with Angular Material Dialog hiding certain elements

In my Node.js Angular project, I am trying to implement a confirm dialog which should be a simple task. Utilizing Material styling to speed up development process. However, upon running the project, the opened dialog appears to be empty: https://i.sstati ...

Sticky table header with scrolling body

I am trying to display a scrollable table list with a fixed header, but I'm having issues with the header content not displaying properly without word wrapping. Additionally, there seems to be a 1px gap above the sticky header when scrolling through t ...

Using the hash(#) symbol in Vue 3 for routing

Even though I am using createWebHistory, my URL still contains a hash symbol like localhost/#/projects. Am I overlooking something in my code? How can I get rid of the # symbol? router const routes: Array<RouteRecordRaw> = [ { path: " ...

Differentiate the types of get and set specified in Vue reactivity properties

After the introduction of Variant Accessors in the latest version of TypeScript (TS 5.1), my interest peaked in creating composables like the one below: export function useRouteQueryParam(param: MaybeRef<string>): WritableComputedRef<string | null ...

What are some methods for retrieving RTK Query data beyond the confines of a component?

In my React Typescript app using RTK Query, I am working on implementing custom selectors. However, I need to fetch data from another endpoint to achieve this: store.dispatch(userApiSlice.endpoints.check.initiate(undefined)) const data = userApiSlice.endpo ...

Error in TypeScript due to object being undefined

Exploring TypeScript and facing a challenge with setting properties in an Angular component. When I attempt to define properties on an object, I encounter an error message: ERROR TypeError: Cannot set property 'ooyalaId' of undefined Here is ho ...

What is the reason for the array length view not updating when a new object is added?

I am dealing with an array of objects and the length is displayed using this code snippet: <strong *ngIf="cart">{{ cart.length }}</strong> Even though when I add items to the array, both the array and its length are showing correctly ...

Issue with clicking the login button in Protractor with TypeScript

I have set up Page objects for the home page and login page. As I proceed with my test cases, I am encountering an issue with the login button. During the execution of my test cases, the login button is not responding to clicks. Has anyone else faced sim ...

Transform a JSON into the necessary structure using TypeScript

I just started learning Angular 6 and TypeScript. The backend API call returns data in the following format. > res = [{ > "metadata": { > "lastGpSyncTime": "2000-11-21T16:07:53", > "dataFro ...

React Typescript Mui causing `onBlur` event to trigger with every change occurring

I'm currently developing a front-end application using Typescript and React with MUI. The form code I have written is as follows: <TextField label="Password" value={this.state.password} placeholder="Choose a password" type="password" onC ...

Using Jest: A guide to utilizing a mocked class instance

When working on my frontend React application, I decided to use the auth0-js library for authentication purposes. This library provides the WebAuth class which I utilize in my code by creating an instance like so: import { WebAuth } from 'auth0-js&ap ...

Having Trouble with Ionic 2's Loading Controller

In my attempt to utilize the recently added LoadingController in this scenario: let loading=this.load.create({ content: "Connexion au serveur Migal en cours..." }); loading.present(); this.http.get(this.urlCheckerForm.value.migalUrl+'/action/Mobi ...

Converting an object to a dot notation string in Typescript types, excluding the innermost child

I am attempting to retrieve the appropriate typescript types using dot notation, excluding the deepest child. After some searching, I came across a helpful resource at Typescript string dot notation of nested object, which partially solved my issue. Howev ...