<repo_name>ranjanpandeysbp/recipe-app<file_sep>/src/app/recipe.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
 
@Injectable({
  providedIn: 'root'
})
export class RecipeService {

  private baseUrlApi = "https://recipeapi2021.herokuapp.com";

  constructor(private http: HttpClient) {}

  registerUser(user: Object): Observable < Object > {
    return this.http.post(`${this.baseUrlApi}` + `/api/v1/auth/register`, user);
  }

  login(user: Object): Observable < Object > {
    return this.http.post(`${this.baseUrlApi}` + `/api/v1/auth/login`, user);
  }

  getRecipe(id: number): Observable < Object > {
    let data = JSON.parse(localStorage.getItem("data"));
    let header = {
      headers: new HttpHeaders()
        .set('Authorization',  `Bearer ${data.token}`)
    }
    return this.http.get(`${this.baseUrlApi}`+`/api/v1/users/${data.userId}/recipes/${id}`, header);
  }

  createRecipe(recipe: Object): Observable < Object > {
    let data = JSON.parse(localStorage.getItem("data"));
    let header = {
      headers: new HttpHeaders()
        .set('Authorization',  `Bearer ${data.token}`)
    }
    return this.http.post(`${this.baseUrlApi}` + `/api/v1/users/${data.userId}/recipes`, recipe, header);
  }

  updateRecipe(value: any): Observable < Object > {
    let data = JSON.parse(localStorage.getItem("data"));
    let header = {
      headers: new HttpHeaders()
        .set('Authorization',  `Bearer ${data.token}`)
    }
    return this.http.put(`${this.baseUrlApi}`+ `/api/v1/users/${data.userId}/recipes`, value, header);
  }

  deleteRecipe(id: number): Observable < any > {
    let data = JSON.parse(localStorage.getItem("data"));
    let header = {
      headers: new HttpHeaders()
        .set('Authorization',  `Bearer ${data.token}`)
        .set('responseType', 'text')
    }
    return this.http.delete(`${this.baseUrlApi}`+ `/api/v1/users/${data.userId}/recipes/${id}`, header);
  }

  getRecipesList(): Observable < any > {
    let data = JSON.parse(localStorage.getItem("data"));
    let header = {
      headers: new HttpHeaders()
        .set('Authorization',  `Bearer ${data.token}`)
    }
    return this.http.get(`${this.baseUrlApi}`+ `/api/v1/users/${data.userId}/recipes`, header);
  }

  getIngredientsList(): Observable < any > {
    let data = JSON.parse(localStorage.getItem("data"));
    let header = {
      headers: new HttpHeaders()
        .set('Authorization',  `Bearer ${data.token}`)
    }
    return this.http.get(`${this.baseUrlApi}`+ `/api/v1/ingredients`, header);
  }

  getRecipesByName(name: string): Observable < any > {
    return this.http.get(`${this.baseUrlApi}/name/${name}`);
  }

  deleteAll(): Observable < any > {
    return this.http.delete(`${this.baseUrlApi}` + `/delete`, {
      responseType: 'text'
    });
  }
}
<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Recipe Management App';
  description = 'Recipe App helps in managing the recipes'
  showMenu: any;
  constructor(private router: Router) {

  }

  ngOnInit() {
    let data = JSON.parse(localStorage.getItem("data"));
    if(data){
      this.showMenu = true;
    }else{
      this.showMenu = false;
    }
    this.router.onSameUrlNavigation = 'reload';
    alert("Important Info: Please click on Login button and use Username=ranjan and Password=<PASSWORD> OR click on Register button for new account");
  }

  logout(event) {
    localStorage.clear();
    this.router.navigate(['login']);
  }
}
<file_sep>/src/app/register/register.component.ts
import { Component, OnInit } from '@angular/core';
import { RecipeService } from '../recipe.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { User } from '../user';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  user: User = new User();
  form: FormGroup;
  errMessage: any;
  message: any;
  showMenu: any;

  constructor(private recipeService: RecipeService, private formBuilder: FormBuilder) { 

  }

  ngOnInit() {

    let data = JSON.parse(localStorage.getItem("data"));
    if(data){
      this.showMenu = true;
    }else{
      this.showMenu = false;
    }

    this.form = this.formBuilder.group({
      name: [null,  [Validators.required, Validators.minLength(1)]],
      username: [null, [Validators.required, Validators.minLength(1)]],
      email: [null, [Validators.required, Validators.minLength(1)]],
      password: [null, [Validators.required]],
      phone: [null,  [Validators.required, Validators.minLength(1)]],
    });
  }

  onSubmit() {
    this.message = "";
    this.errMessage = "";
    this.recipeService.registerUser(this.user)
    .subscribe(data => this.message = data["message"], error => this.errMessage = error["error"]["message"]);
  }

}
<file_sep>/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';

import { RecipeService } from '../recipe.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { User } from '../user';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  user: User = new User();
  form: FormGroup;
  errMessage: any;
  showMenu: any;

  constructor(private router: Router, private recipeService: RecipeService, private formBuilder: FormBuilder) { 

  }

  ngOnInit() {
    let data = JSON.parse(localStorage.getItem("data"));
    if(data){
      this.showMenu = true;
    }else{
      this.showMenu = false;
    }
    this.form = this.formBuilder.group({
      username: [null, [Validators.required, Validators.minLength(1)]],
      password: [null, [Validators.required]],
    });
    this.router.onSameUrlNavigation = 'reload';
  }

  onSubmit() {
    this.recipeService.login(this.user)
    .subscribe((data) => {
      console.log(data);
      localStorage.setItem("data", JSON.stringify(data));
      this.router.navigate(['recipe']);
    }, (error) => {
      debugger;
      if(error["error"]["status"] == 401){
        this.errMessage = "Invalid credentials";
      }
    });
  }

}
<file_sep>/README.md
The application is the frontend part of Recipe management application
You can register and login and manage recipes

Two ways to acess the application:
----------------------------------
1. Access the hosted url: **https://ranjanpandeysbp.github.io/**

2. Run the application locally:
a. Git clone https://github.com/ranjanpandeysbp/recipe-app.git
b. From root run command **npm install**
c. From root run command **ng serve**
d. Open browser access http://localhost:4200/
e. Popup will appear with login details instruction, please use the instruction.

This frontend is connected to heroku hosted api:
https://recipeapi2021.herokuapp.com/v2/api-docs

If you want to run the backend API locally by following below steps:
https://github.com/ranjanpandeysbp/recipes-api

Than in this project(Frontend) please change the base url from heroku to your local backend API in file **recipe.service.ts**
Change the local url in **baseUrlApi** variable.<file_sep>/src/app/recipe.ts
import { Ingredients } from "./ingredients";

export class Recipe {
  id: number;
  recipeName: string;
  dishType: string;
  creationDateTime: Date;
  noOfPeople: number;
  ingredientEntityList: Ingredients[];
  cookingInstruction: string;
}
