0% found this document useful (0 votes)
20 views

Angular Project Notes

The document explains how OData URLs are created and used to make requests. It shows code for constructing OData filters and URLs based on parameters and making GET requests. It also provides details on authentication for an OData service and handling the response.

Uploaded by

bhumism303
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Angular Project Notes

The document explains how OData URLs are created and used to make requests. It shows code for constructing OData filters and URLs based on parameters and making GET requests. It also provides details on authentication for an OData service and handling the response.

Uploaded by

bhumism303
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

# How Odata URL created and worked?

code:

//Bugdet.component.ts

onNumberOfYearsChange(selectedItems:any) {

debugger

this.selectedNumberOfYears = selectedItems[0].item_id;

var previousYear=this.getPreviousYears();

let businessUnits = this.myForm.get('idBusinessUnit')!.value.map((item: any) => {

return { title: item, value: item }; // Assuming 'title' and 'value' are the same as in selectedItems

});

let ODataFilters = {

"Company": this.myForm.get('idCompany')!.value,

"BuisnessUnit":businessUnits,

"PreviousYearsArr":previousYear

};

sessionStorage.setItem("ODataFilters", JSON.stringify(ODataFilters));

this.myForm.get('percentage')?.reset();

this.dataFetching();

this.call_OData_ACC_BAL();

this.updateSelectYearDropdownData();

call_OData_ACC_BAL(){

let q:any;

const storedData = sessionStorage.getItem("ODataFilters");

if (storedData) {

try {

q = JSON.parse(storedData);
if (typeof q !== 'object' || Array.isArray(q)) {

throw new Error('Invalid JSON format'); // If parsed data is not an object

catch (error) {

console.error('Error parsing JSON from session storage:', error);

q = {};

this.loading = true;

// var aFilterFromYear = "";

// aFilterFromYear += "gjahr ge '" + q.PreviousYearsArr[0]+ "'";

var aFilter = "";

var aFilter2 = "";

aFilter += "gjahr ge '" + q.PreviousYearsArr[0]+ "'";

if (q.Company.length > 0) {

var Count = 0;

q.Company.forEach((x: any) => {

if (Count == 0) {

aFilter += this.common.add(aFilter , "and") + "rbukrs eq '" + x.title + "'";

aFilter2 += this.common.add(aFilter2, "and") + "rbukrs eq '" + x.title + "'";

else {

aFilter += this.common.add(aFilter, "or") + "rbukrs eq '" + x.title + "'";

aFilter2 += this.common.add(aFilter2, "or") + "rbukrs eq '" + x.title + "'";

Count++;
})

if(q.BuisnessUnit.length > 0){

var Count = 0;

q.BuisnessUnit.forEach((x:any)=>{

if(Count == 0)

aFilter += this.common.add(aFilter, "and") +"(bizunit eq '"+x.title +"'";

aFilter2 += this.common.add(aFilter, "and") +"(bizunit eq '"+x.title +"'";

else

aFilter += this.common.add(aFilter, "or") +"bizunit eq '"+x.title +"'";

aFilter2 += this.common.add(aFilter, "or") +"bizunit eq '"+x.title +"'";

Count++;

})

aFilter += ")";

let selectedYear = q.PreviousYearsArr[0];

var oDataUrl = "/xSOLVIExACplanact?$format=json&$filter=" + aFilter;

console.log("odata url : "+ oDataUrl);

this.odataService.oData_ACC_BAL(oDataUrl).subscribe((x:any)=>{

this.loading = false;

this.dataSet = []
this.dataSet = x.d.results;

this.monthWisePNLDataset(this.dataSet,selectedYear);

this.monthWiseBalanceSheetDataSet(this.dataSet,selectedYear);

})

//topbar.ts

localStorage.setItem('mapParameter', '/ACPLANACT_CDS');

//odata.service.ts

import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Injectable } from '@angular/core';

import { environment } from '../../environments/environment';

import { catchError, tap } from 'rxjs/operators';

import { throwError } from 'rxjs';

@Injectable({ providedIn: 'root' })

export class OdataService {

constructor(private http: HttpClient) {}

oData_ACC_BAL(odataUrl: string) {

var mapParameter =localStorage.getItem('mapParameter');

console.log("mapParameter", mapParameter);

var url = document.location.origin + mapParameter+ odataUrl;

console.log("url", url)

// res.setHeader('Access-Control-Allow-Origin', '*');

var result =this.http.get<any>(url);


return result;

ZSOL_MASTER_DATA() {

debugger;

var location = document.location.origin;

var url = location + '/sap/opu/odata/sap/ZSOL_MASTER_DATA_CDS/ZSOL_MASTER_DATA';

const username = 'Solsynch';

const password = 'Sol23@S4prddb1';

const authString = 'Basic ' + btoa(username + ':' + password);

const headers = new HttpHeaders({

'Authorization': authString,

'Access-Control-Allow-Origin' : '*'

});

// res.setHeader('Access-Control-Allow-Origin', '*');

var result =this.http.get<any>(url, { headers });

return result;

- Explanation of oData_ACC_BAL

• oData_ACC_BAL(odataUrl: string) {: This line defines a method named oData_ACC_BAL within


the OdataService class. The method takes a single parameter odataUrl of type string. This
method is responsible for making an HTTP GET request to a specified OData URL.

• var mapParameter = localStorage.getItem('mapParameter');: This line retrieves a value from the


browser's local storage with the key 'mapParameter' and assigns it to the variable
mapParameter.
• console.log("mapParameter", mapParameter);: This line logs the value of mapParameter to the
console for debugging purposes.

• var url = document.location.origin + mapParameter + odataUrl;: This line constructs the full URL
for the OData request by concatenating the origin of the current document, the value of
mapParameter, and the odataUrl parameter.

• document.location.origin is a property in JavaScript that returns the origin (protocol, hostname,


and port number) of the current URL.

• For example, if the current URL in the browser is https://www.example.com:8080/path/to/page,


then document.location.origin will return https://www.example.com:8080. This property is often
used when constructing URLs for making requests to the same origin as the current page. In the
provided code, document.location.origin is used to dynamically obtain the origin of the current
page and then construct a full URL by appending additional path segments or parameters.

• console.log("url", url);: This line logs the constructed URL to the console for debugging purposes.

• var result = this.http.get<any>(url);: This line makes an HTTP GET request to the constructed URL
using Angular's HttpClient service. The get method returns an observable that emits the HTTP
response.

• return result;: This line returns the observable result from the method oData_ACC_BAL.

-Explanation of ZSOL_MASTER_DATA :

• var location = document.location.origin;: This line retrieves the origin (protocol, hostname, and
port number) of the current URL and stores it in the variable location. It is similar to what we
discussed earlier with document.location.origin.

• var url = location + '/sap/opu/odata/sap/ZSOL_MASTER_DATA_CDS/ZSOL_MASTER_DATA';: This


line constructs the URL for the OData service. It concatenates the current origin (location) with
the path to the OData service endpoint.

• const username = 'Solsynch'; and const password = 'Sol23@S4prddb1';: These lines define the
username and password for basic authentication to access the OData service. It seems like the
service requires basic authentication.

• const authString = 'Basic ' + btoa(username + ':' + password);: This line constructs the
Authorization header value for basic authentication. It encodes the username and password in
Base64 format as per the basic authentication standard.

• const headers = new HttpHeaders({ 'Authorization': authString, 'Access-Control-Allow-Origin' : '*'


});: This line creates an instance of HttpHeaders class and initializes it with the Authorization
header containing the encoded credentials and the Access-Control-Allow-Origin header set to *.
The latter header allows cross-origin resource sharing (CORS) for all origins.

• var result = this.http.get<any>(url, { headers });: This line makes an HTTP GET request to the
constructed URL (url) using Angular's HttpClient service (this.http). It includes the custom
headers (headers) for authentication and CORS. The <any> type parameter indicates that the
response body is expected to be of any type.

• return result;: This line returns the result of the HTTP GET request as an observable. The caller of
this method can subscribe to this observable to receive the response from the server
asynchronously.

• In summary, this function constructs a URL for an OData service endpoint, sets up basic
authentication headers, makes an HTTP GET request to the endpoint using Angular's HttpClient,
and returns the result as an observable.

# How to Redirect After Logout:


- To issue in web applications where the browser's back button can take the user to a previously visited
page even after logging out.

-To prevent this behavior, you can employ various strategies:

• Disable Caching: Ensure that the browser doesn't cache pages that require authentication. You
can do this by setting appropriate HTTP headers to disable caching for sensitive pages.

• Redirect After Logout: After successfully logging out, redirect the user to a page that doesn't
cache content. For example, you could redirect them to the login page or a neutral landing page
that doesn't have sensitive information.

• Use Route Guards: In Angular, you can implement route guards to prevent unauthorized access
to certain routes. You can create an AuthGuard that checks if the user is logged in before
allowing access to certain routes. If the user is not logged in, they'll be redirected to the login
page.

• Clear Session Data: Upon logout, make sure to clear any session data or tokens that indicate the
user is logged in. This ensures that even if the user navigates back using the browser's history,
they won't be considered authenticated.

Code:-

-// auth.guard.ts

import { Injectable } from '@angular/core';

import { CanActivate, Router } from '@angular/router';

import { AuthenticationService } from './_services/authentication.service';

@Injectable({

providedIn: 'root'

})
export class AuthGuard implements CanActivate {

constructor(private authenticationService: AuthenticationService, private router: Router) {}

canActivate(): boolean {

if (this.authenticationService.isLoggedIn()) {

return true;

} else {

this.router.navigate(['/userLogin']);

return false;

-// authentication.service.ts

import { Injectable } from '@angular/core';

import { HttpClient, HttpHeaders } from '@angular/common/http';

import { BehaviorSubject, Observable } from 'rxjs';

import { map } from 'rxjs/operators';

import { environment } from '../../environments/environment';

import { User } from '../_models';

@Injectable({ providedIn: 'root' })

export class AuthenticationService {getCurrentUser(): any {

// console.log("currentuser: ", JSON.parse(localStorage.getItem('currentUser')));

if (typeof localStorage !== 'undefined') {

return localStorage.getItem('currentUser');

}
isLoggedIn(): boolean {

// Check if user is logged in based on your authentication logic

// For example, check if a token is present in localStorage

return !!localStorage.getItem('currentUser');

logout() {

// Clear session data upon logout

localStorage.removeItem('currentUser'); // Remove user data upon logout

-//userlogout.component.ts

import { Component } from '@angular/core';

import { AuthenticationService } from '../_services/authentication.service';

import { Router } from '@angular/router';

@Component({

selector: 'app-user-logout',

templateUrl: './user-logout.component.html',

styleUrl: './user-logout.component.css'

})

export class UserLogoutComponent {

constructor(private authenticationService: AuthenticationService, private router: Router) {

this.authenticationService.logout();

this.router.navigate(['/userLogin']);

You might also like