Creating new Angular2 Observables - Subscribing to undefined developments

Is it a scoping issue or a problem with how my observables are set up? Can you assist me in figuring it out?

To explain my logic: My goal is to first check if the data is available locally before making an http.get request for it. I want to return the local data if it exists, and I thought of returning an observable so that I can subscribe to the function's output whether it returns local or remote data. Any feedback on this approach would be great!

I am using Cory Rylan's blog post (https://coryrylan.com/blog/angular-2-observable-data-services) as a guide to implement my own observable. However, I am facing difficulty in defining my Observer in the getData function.

You can find Cory's working demo here: Cory's Demo

Here is my non-working demo: My Demo - In the log, you can see that this._dataObserver in the service is undefined, unlike in Cory's example where it is defined. This is causing issues for me.

Below are snippets from the code:

App.ts

@Component({
  selector: 'my-app',
  template: `
    <landing-page></landing-page>    
  `,
  providers: [DataService],
  directives: [LandingPageComponent]
})
export class App {
  constructor() { }
}

bootstrap(App, [HTTP_BINDINGS])
  .catch(err => console.error(err));

LandingPageComponent.ts

@Component({
  selector: 'landing-page',
  template : `
    hello
  `,
})
export class LandingPageComponent implements OnInit{
  data : Observable<any[]>;
  constructor(
    private _dataService : DataService
  ) { }

  ngOnInit() {
    this.data = this._dataService.data$;
    this._dataService.getData();
  }
}

DataService

@Injectable()
export class DataService {

   data$ : Observable<any[]>; // data stream
   private _baseUrl: string;
   private _dataObserver : Observer<any[]>;
   private _dataStore : {
    data : any[]
   };

  constructor (
    private _http: Http
  ) {
    this._baseUrl  = 'http://56e05c3213da80110013eba3.mockapi.io/api';
    this.data$ =  new Observable(observer => this._todosObserver = observer).share();
    this._dataStore = { data: [] };
  }

  /** **************
  * Public functions
  *****************/

  getData () {
    this._http.get(`${this._baseUrl}/todos`)
      .map(data => data.json())
      .subscribe( data => {
      this._dataStore.data = data;
      console.log(this._dataObserver);   //<------ This is undefined for me!
      this._dataObserver.next(this.data);
    },
    error => {
      console.log('couldn\'t load data! ' + error );
    });

  }

}

Any insights you have would be greatly appreciated.

Answer №1

The reason why _dataObserver is null is because you have not subscribed to the associated observable. It's important to remember that observables are lazy...

You can try the following solution:

ngOnInit() {
  this.data = this._dataService.data$.subscribe(data => { // <-----
    console.log(data);
  });
  this._dataService.getData();
}

Note:

Furthermore, there seems to be a typo in your code snippet:

this.data$ =  new Observable(observer => this._todosObserver = observer).share();

You should replace _todosObserver with _dataObserver:

this.data$ =  new Observable(observer => this._dataObserver = observer).share();

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

Angular2 - Model not being refreshed by Directive

I have implemented a directive on an HTML input box to handle numeric values. The directive is meant to "clean" the number (removing commas, dollar signs, etc) when a user pastes a number into the textbox. Although the cleaning code works properly, the iss ...

Tips on avoiding the conversion of the ✳ symbol into an emoji

My issue lies in my ✳ (Eight-Spoked Asterisk) symbol being converted to an emoji on iOS/android devices. Find more about the Eight-Spoked Asterisk Emoji here. Could someone guide me on how to prevent the normal symbol ✳ from being transformed into an ...

angular $stateprovider malfunctioning and causing unexpected behavior

Currently, I am utilizing angular's $stateProvider to enable routing within my application. The main HTML file is index.html and I am updating the HTML content inside it with the following code... app.config(function($stateProvider, $urlRouterProvide ...

What is the best way to incorporate Tradingview's JavaScript into the render function of a React Typescript

I'm trying to incorporate some widgets into my Typescript React component. Here is the embed code export default class App extends React.Component { render(): ReactNode { return ( <div> Chart test <div className= ...

Discover how to capture and process POST form data in Angular originated from external sources

I am currently building a website that utilizes Java for the backend and Angular for the frontend. I have encountered a scenario where external websites may transmit data to my site via POST form submissions. For example, ▼ General    & ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

How come a null variable continues to widen to type any even when strictNullChecks is enabled?

According to the TypeScript Documentation, if strictNullChecks is true, there should be no type widening. Also, the typeof nul should be null. let nul = null; // typeof nul = any let undef = undefined; // typeof undef = any Check it out in the Playground ...

What causes the form to consistently show as invalid once it has been submitted?

register.html : <form [formGroup]="signupForm" (submit)="onSubmit()" class="form-detail"> <h2>Registration Form</h2> <div class="form-row-total"> <div class="form-row"> <in ...

AngularJS form submission with and without page refresh

Looking to implement an AngularJS form directive where, if on /home page, redirect to /search/term and if already on /search page, submit without refreshing the page by simply changing the location. I am able to do both separately, but struggling to writ ...

Angular's Integration with PayPal for Shipping Costs

I am facing an issue with my e-commerce website where the receipt only displays the total payment of the items purchased. I have searched for an SDK that supports Angular or TypeScript PayPal integration, but could only find one for JavaScript which did ...

Requirements for Method Decorators - The complete path of the class module using the decorator must be provided

Upon running the decorator (method decorators) function, we are provided with access to target, methodName, and descriptor. I am seeking the module path for target in this specific scenario. Essentially, I want the file path that points to the module that ...

Angular Tip: Display data in a dropdown using a select element

When I have two select elements and want to display values if they exist: page.ts import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app ...

Typegoose's representation of modifying data

Recently, I delved into the world of NestJS and kickstarted a sample project. To integrate MongoDB seamlessly, I opted for Typegoose. A useful online tutorial () caught my eye, illustrating how to employ abstractions with base typegoose models. Hence, my ...

Enable the acceptance of various validator patterns within Angular Material 2

I'm using md-error in angular material to validate user inputs from the client side. Currently, I am trying to validate an input field that accepts two types of patterns: Pattern 1: Accept the first 9 characters as numbers followed by the 10th ch ...

What is the best way to verify a modification on an observable within a service mock?

Currently, I am faced with the task of testing a backend service stub that returns an observable. The method in question is as follows: public postStatus(handle: string): Observable<StatusReturn>{ setTimeout(() => { this.result = { ...

Library for Nodejs that specializes in generating and converting PDF/A files

Is there a library available that can convert/create a PDF/A file? I've been searching for solutions but the existing answers suggest using an external service or provide no response at all. I heard about libraries in other languages like ghostscriptP ...

Having difficulty ensuring DayJs is accessible for all Cypress tests

Currently embarking on a new Cypress project, I find myself dealing with an application heavily focused on calendars, requiring frequent manipulations of dates. I'm facing an issue where I need to make DayJs globally available throughout the entire p ...

Manually close the AntD Menu without using any shortcuts

I'm facing a unique situation with my table implemented using antd. Each row has a dropdown menu that opens a modal upon clicking. To ensure the dropdown menu doesn't trigger the row click event, I used stopPropagation on the menu item click. Eve ...

How to selectively load specific scripts in index.html with the use of angular.js

Let me address a problem I'm facing with a large development project. It seems that the current setup does not function properly on Internet Explorer. My idea is to only load files that are compatible and do not generate errors when accessed through I ...

I developed a real estate listing web application using AngularJS, where I chose to use the $http service to fetch data. Unfortunately, the data retrieval process seems to be failing. Can someone help me identify the issue?

Hey there, I have identified three files which seem to be at the root of the problem. Instead of using POST, GET, PUT, DELETE methods, I am intentionally experimenting with $http. Let's take a look at mansionsController.js file: angular .module( ...