Home > other >  angular failing in mock data testing with error 'Cannot read property 'subscribe' of
angular failing in mock data testing with error 'Cannot read property 'subscribe' of

Time:06-23

I have created a dummy service to return some dummy data, then get it called by a component ts file. But i got error like 'Cannot read property 'subscribe' of undefined'.

Found a few posts with similar error,but still can not figure out how to correct mine.

upload.service.ts:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { InvalidSOEIDModel } from '../Uploadmodel/uploadmodel'
import {of} from 'rxjs';

@Injectable()
export class UploadService {
  ReturnData: Observable<InvalidSOEIDModel[]>;

 UploadDataReturn(): Observable<InvalidSOEIDModel[]> {
    const ReturnData = { data:
      [
      {
        SOEID: "AAAAA"
      },
      {
        SOEID: "BBBBB"
      }
    ]
  };
 
    return this.ReturnData;
  }
}

file-load-init.component.ts:

import { BaseComponent } from '../../common/scripts/baseComponent';
import { Component, OnInit} from '@angular/core';
import { HttpClientModule, HttpClient, HttpHandler } from '@angular/common/http';
import { UploadService } from '../UploadService/upload.service';
import { InvalidSOEIDModel } from '../Uploadmodel/uploadmodel';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-file-load-init',
  templateUrl: './file-load-init.component.html',
  styleUrls: ['./file-load-init.component.css']
})
export class FileLoadInitComponent implements OnInit {
  
  InvalidSOEIDModel:InvalidSOEIDModel[];
  ngOnInit(): void {
  }

  constructor(private http: HttpClient,
              private UploadService: UploadService,) {}


  OnUpload(){
    
  this.GetSOEIDVerifyData();
  };


  private   GetSOEIDVerifyData(){  
    this.UploadService.UploadDataReturn()
     .subscribe((res: any[]) => {
          console.log(res);
        }
     )}

Can someone please help to check? I'm new to angular.

CodePudding user response:

RxJS Operator: of()

To return an observable you can use the RxJS operator of.

Change this in your service this :

uploadDataReturn(): Observable<InvalidSOEIDModel[]> {
  return of([
    {
      SOEID: "AAAAA"
    },
    {
      SOEID: "BBBBB"
    }
  ]);
}
  • Related