Displaying the value only when the condition is met in Angular

I am working on a feature to display a list of job postings made by HR in an Angular HTML page. The requirement is that when a HR logs in, they should only see the jobs they have posted, not all the jobs posted by all HRs. I plan to accomplish this by comparing the HR ID with the foreign key (HrId) in the jobPosting table. If there is a match, then the page should display all the jobs posted by that specific HR. The HR ID will be obtained when the HR logs in, using the access_token stored in Local Storage. Other information can be retrieved using a Get Method that fetches all the jobs.

Below is the code snippet for loading the current user using Local Storage. This will provide the ID of the current HR

loadCurrentUser(){
  const token=localStorage.getItem("access_item");
  const userInfo=token != null ? this.jwtHelperService.decodeToken(token):null;
  const data=userInfo ? {
    UserId:userInfo.UserId,
    UserName:userInfo.UserName,
    Email:userInfo.Email,
    City:userInfo.Company
  }:null;
  this.currentUser.next(data);
  return data;
}

Get Method using Angular and .NET

getAllJobPostings():Observable<JobPosting[]>{
  return this.http.get<JobPosting[]>(this.basicURL+'Main/GetAllJobPostings');
}

Get method using .NET

[HttpGet("GetAllJobPostings")]
public IEnumerable<JobPosting> GetDetails(){
  return Context.JobPosting.ToList();
}

Model Class for Job Posting

export class JobPosting{
  jobid:number=0;
  title:string='';
  hrId:number=0;
  experience:number=0;
  position:string='';
  company:string='';
  ctc:number=0;
  skills:string='';
  description:string='';
}

Database Result Expected Result

If the HrId=2 matches, then only that particular record should be displayed.

Please advise me on how to achieve this and provide suggestions for the code implementation.

Answer №1

It's possible that some of you may not have understood my initial query, so let me break it down. Essentially, I wanted to display data based on the HR ID. For example, if my HR ID is 1, then all the job postings associated with that ID should be visible on the HR Admin page.

See below for the code snippet:


user:any;
hrid:any;
allJobDetails:JobPosting[]=[];
  
constructor(private service:UserServiceService){};

ngOnInit(): void {
    
    this.user=this.service.loadCurrentUser();
   
    this.getJobDetails();
}

getJobDetails()
{
    this.service.getAllJobPostings().subscribe(
      (res:JobPosting[])=>
      {
       for(let r of res)
       {
        if(r.hrId == this.user.UserId)
        {
          this.hrid=r.hrId.toString();
          this.allJobDetails.push(r);
        }
       }
      }
    )
}

Below is the HTML code used:

<div *ngIf="user.UserId === hrid ">
    {{user|json}}

    <div *ngFor="let job of allJobDetails">
        <p>{{job.title}}</p>
        <p>{{job.company}}</p>
    </div>

</div>

By following the above method, you should get the desired outcome by displaying the values from the JobPosting Model Class. I achieved the expected result as outlined in the original question.

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

Is it possible to determine the length of a CryptoStream before decrypting it?

Can the final length of decrypted data be determined before decryption? For example: RijndaelManaged RMCrypto = new RijndaelManaged(); RMCrypto.Padding = PaddingMode.ISO10126; Response.Buffer = false; Response.ClearHeaders(); Response.ClearContent(); Res ...

VSCode Troubleshooting: When TypeScript Doesn't Recognize Installed Libraries

Lately, I've encountered a problem when using TypeScript in VSCode. Whenever I install a new library through npm, TypeScript doesn't seem to acknowledge the library right away. For instance, after adding the query-string library and attempting to ...

Exploring the power of chaining multiple subscriptions in RxJs 6

I have a project using Angular 6, and I'm currently in the process of upgrading rxjs to version 6. In the previous iteration of my app, there was a specific flow where I needed to make sequential calls to observables: 1. Call an observable 2. Perfor ...

Issue with binding nested ViewModels/components in Knockoutjs using TypeScript does not resolve

Struggling with implementing a viewModel within another viewModel in knockout. Any assistance would be greatly appreciated. Using typescript and aiming to have a list of address controls, each with their individual viewmodel. Initially, the project functi ...

Errors have been encountered in the Angular app when attempting to add FormControl based on the data retrieved from the backend

This specific page is a part of my Angular application. Within the ngOnInit method, I make two API calls to retrieve necessary data and iterate through it using forEach method to construct a reactive form. However, I am facing one of two different errors ...

Custom Association in EntityFramework

Consider a scenario where there is a user table and a separate table to log all login attempts (columns: Id (counter), userId, time, and success status). In my Entity Model, I aim to establish two associations - one for successful attempts and another for ...

Is it necessary for me to dispose of MySqlCommand?

Having to add a using statement to each query is a real hassle for me, especially when I need to declare variables outside of the using block and then clear parameters. It's messy and unappealing compared to not disposing of the object. Is it really ...

Best Practices for Organizing Imports in Typescript to Prevent Declaration Conflicts

When working with TypeScript, errors will be properly triggered if trying to execute the following: import * as path from "path" let path = path.join("a", "b", "c") The reason for this error is that it causes a conflict with the local declaration of &ap ...

Invoke the HTTP API from the device application

I need to make an API call to a server that does not have the HTTPS protocol. I came across this post on Stack Overflow: https://stackoverflow.com/questions/57433362/api-calls-made-in-ionic-4-app-not-working-on-android-device The post mentions that HTTP ...

Angular4 provider being integrated into an AngularJS application offers the provider functionality

I have recently migrated my app from AngularJS to Angular4. Now, I want to create a provider in Angular4 and inject it into the app.config in AngularJS. Here is what I currently have: import { UtilsService } from './../utils/utils.service'; imp ...

The action dispatched by "AuthEffects.register$" is not valid and will have no effect

After implementing a new effect for the register action, I encountered the following error message: Effect "AuthEffects.register$" dispatched an invalid action Below is the code for my effect: @Effect() register$ = this.actions$.pipe( ofType<Regis ...

How To Retrieve the Index of a Specific Row and Column in AgGrid (Angular)

Right now, I can retrieve the row data using the gridApi but I am struggling to determine the column index of the selected row. The method this.gridApi.getSelectedRows() does not provide any information about the column index. I would greatly appreciate ...

Creating a generic type in TypeScript that represents a union of keys from type T's properties

Is there a way to determine the result type (TTarget) based on TSource and the provided property names (keyof TSource)? I have this function that copies specified properties to a new object: export declare type PropertyNamesOnly<T> = { [K in keyof ...

The function cloneElement does not share any properties with the type Partial<P> and Attributes

I'm encountering a perplexing issue with my code. When I attempt to call cloneElement with the second parameter being of type Type { foo: number } has no properties in common with type 'Partial<Child> & Attributes', TypeScript thro ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

How can I improve the appearance of a WinForms application when using medium/large fonts in Windows 7?

I am facing an issue with my Windows Forms application that was built using .NET 3.5 and an older version of Infragistics controls. The forms and controls do not look good when viewed in Windows7 with Medium or Large Fonts. I have numerous forms in the app ...

Unable to perform a union operation that combines multiple enums into one

Here is a basic example: export enum EnumA { A = 'a', } export enum EnumB { A = 'b', } export class SomeEntity { id: string; type: EnumA | EnumB; } const foo = (seArray: SomeEntity[]) => { seArray.forEach((se) => { ...

Tips for integrating Postman API with Angular 4

app.component.ts: import { Component } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-root', templateUrl: './app.component ...

Issue encountered when attempting to access interface field in HTML template of Angular 2

export interface Candidate { name: string; surname: string; gender: boolean; dateOfBirth: Date; placeOfBirth: string; originRegion: string; originDivision: string; originSubDivision: string; employmentSituation: string; typeHandicap: st ...

Issues with IAM security credentials are being encountered when using Powertools for AWS Lambda (.NET) in one Visual Studio project, while it is functioning properly in another project

Currently, I am facing an issue with my Visual Studio 2022 net6 AWS Serverless Application Model (SAM) project. When I attempt to test a function in my unit testing project, I encounter an IAM credentials exception. This project was created using Powertool ...