Angularjs print value in localstorage - angularjs

Angularjs how to print name in localstorage
i try this console.log($scope.storageData.name); //output is Undifiend
var user = angular.toJson(response.data.user);
localStorage.setItem('user', user);
$rootScope.authenticated = true;
$scope.storageData = localStorage.getItem("user");
console.log($scope.storageData);
console.log($scope.storageData.name);
output
{"id":20,"name":"test","email":"test#gmail.com","roles":"","created_at":"2018-02-27 10:07:53","updated_at":"2018-03-02 06:51:26"}

You need to parse it to an object before accessing name
$scope.storageData = JSON.parse(localStorage.getItem("user"));

You need to parse it to an object first. Your this line here:
$scope.storageData = localStorage.getItem( "user" );
Should be changed with this:
$scope.storageData = JSON.parse( localStorage.getItem( "user" ) );

Related

React-URLSearchParams returning Null object

I am using the following code to retrieve query parameters from URL but URLSearchParams returns an empty object.
PS: uselocation.search returning correct output.
const stringdata = useLocation().search
const queryparameter = new URLSearchParams(stringdata)
console.log("query parameter :", queryparameter)
const query = queryparameter.get('q');
var url_string = `http://localhost:3000/recipes${query}`
You can try using window.location.search over user search params.
That should look something like:
const queryParams = new URLSearchParams(window.location.search);
const query = queryParams.get('q');
let url_string = `http://localhost:3000/recipes${query}`;
The search property returns the querystring part of a URL, including the question mark (?).
const queryParams = new URLSearchParams(window.location.search);
Then you need to check if queryparameter.get('q') exists, otherwise it will return null and will append null to url.
let query;
if(queryParameter.has('q')){
query = queryparameter.get('q');
}
then
var url_string = `http://localhost:3000/recipes/${query}`

TypeError: this is undefined in rect js while passing BigNumber in solana RPC Request

i am getting this is undefined at BN while making RPC request to a function in solana smart contract
'''
let token1Amount = BN(token1_amount);
let token2Amount = BN(token2_amount)
const add_liquidity = await router_program.rpc.addLiquidity(
token1Amount,
token2Amount,
{
accounts: {
// poolAccount: pool_Account.publicKey, //account which stores the individual pair data
userToken1Account: usetoken1_account,
userToken2Account: usetoken2_account,
poolToken1Account: new PublicKey(tokenaccount_1),
poolToken2Account: new PublicKey(tokenaccount_2),
owner: provider.wallet.publicKey,
tokenProgram: TOKEN_PROGRAM_ID,
// systemProgram : SystemProgram.programId ,
// associatedTokenProgram: spl.ASSOCIATED_TOKEN_PROGRAM_ID,
// rent: anchor.web3.SYSVAR_RENT_PUBKEY,
tokensProgram: TOKEN_ID,
// poolProgram: pair.programId,
// pairAccount: pairAccount.publicKey
},
// signers: [provider]
}
);
'''
This is a shot in the dark, but I think you need new so that your BNs have a this context, so instead try:
let token1Amount = new BN(token1_amount);
let token2Amount = new BN(token2_amount);

Setting Postman env variable based on the repsonse where certain criteria is met

When I get a response in Postman, I want to be able to set an environment variable (using
pm.environment.set("variable_key", "variable_value");
when a condition is met from the response array.
So the requirements:
set an environment variable named idForAbc to the value of someArray.id where someArray.criteria = "ABC" (so idForAbc = 1)
set an environment variable named idForXyz to the value of someArray.id where someArray.criteria = "XYZ" (so idForXyz = 2)
Here is my sample response:
You can choose one of 2 ways:
const res = pm.response.json();
const abc = res.someArray.find(e => e.criteria === "ABC");
if(abc){
pm.environment.set(`idFor${abc.criteria}`,abc.id)
}
const xyz = res.someArray.find(e => e.criteria === "XYZ");
if(xyz){
pm.environment.set(`idFor${xyz.criteria}`,xyz.id)
}
or
const res = pm.response.json();
function saveVarByCriteria(arr, value){
const obj = arr.find(e => e.criteria === value);
if(obj){
pm.environment.set(`idFor${obj.criteria}`, obj.id)
}
}
saveVarByCriteria(res.someArray, "ABC");
saveVarByCriteria(res.someArray, "XYZ");

Efficient way to use display the results from the fetch?

I am started learning reactjs. I have fetch result from the given API https://lichess.org/api/user/nihalsarin2004 which shows the profile of Lichess User. (Here nihalsarin2004). But for using every detail, I have coded them as below:
let fName = JSON.stringify(data?.profile?.firstName);
let lName = JSON.stringify(data?.profile?.lastName);
let totalGames = JSON.stringify(data?.count?.all);
let totalWins = JSON.stringify(data?.count?.win);
let totalDraws = JSON.stringify(data?.count?.draw);
let totalLoss = JSON.stringify(data?.count?.loss);
let userLink = JSON.stringify(data?.url);
.
.
.
.
.
let blitzRating = JSON.stringify(data?.perfs?.blitz?.rating);
let bulletRating = JSON.stringify(data?.perfs?.bullet?.rating);
let rapidRating = JSON.stringify(data?.perfs?.rapid?.rating);
let classicalRating = JSON.stringify(data?.perfs?.classical?.rating);
let chess960Rating = JSON.stringify(data?.perfs?.chess960?.rating);
let antichessRating = JSON.stringify(data?.perfs?.antichess?.rating);
let checkRating = JSON.stringify(data?.perfs?.threeCheck?.rating);
let atomicRating = JSON.stringify(data?.perfs?.atomic?.rating);
let hordeRating = JSON.stringify(data?.perfs?.horde?.rating);
And then using these variables in react components ?
Do we any alternative for this ?
Use Destructuring Assignment and assign a new variable names in the destructuring:
let { firstName: fName, lastName: lName } = data?.profile;
let { all: totalGames, win: totalWins /* and so on */ } = data?.count;
You can de-structure them as follows:
if(!data.profile){
// check if there is data and profile
// same for other keys in data obj
return null
}
let {firstName, lastName} = data.profile
let {all,win, draw, loss} = data.count
// so on...
Note: whenever you are de-structuring any variable from an object make sure you name that variable same as key that you want to extract
for example:
let obj={
name:"John",
age:20,
}
// if you want to destructure obj you can do following
let {name, age}=obj
//variable names in {} should be same as key in obj

TokenCache: No matching token was found in the cache, Azure AD Api

I'd like to use Azure AD Api and I couldn't acquire token some reason. I have two methods, and I got this after calling:
TokenCache: No matching token was found in the cache iisexpress.exe Information: 0
Here's my code:
public string GetToken()
{
string authority = "https://login.microsoftonline.com/{tenantId}/";
string clientId = "";
string secret = "";
string resource = "https://graph.windows.net/";
var credential = new ClientCredential(clientId, secret);
AuthenticationContext authContext = new AuthenticationContext(authority);
//I think the problem is here:
var token = authContext.AcquireTokenAsync(resource, credential).Result.AccessToken;
return token;
}
public string MakeRequest()
{
string accessToken = GetToken();
var tenantId = "";
string graphResourceId = "https://graph.windows.net/";
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, tenantId);
ActiveDirectoryClient client = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));
foreach (var user in client.Users.ExecuteAsync().Result.CurrentPage)
Console.WriteLine(user.DisplayName);
var client1 = new HttpClient();
var uri = "https://graph.windows.net/" + tenantId + "/users?api-version=1.6";
client1.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var response = client1.GetAsync(uri).Result;
var result = response.Content.ReadAsStringAsync().Result;
return result;
}
I don't know what's the problem, and I didn't find any great hint, under other questions and a little explanation would be helpful. I'd like to understand this part, of course.
//When you are calling
Main() { Method_A() }
aync Method_A() { await Method_B() }
Task < T > Method_B() { return T; }
//It will through the error. //Need to keep Mehtod_B in another Task and run.
// Here I am avoiding few asyncs
Main() { Method_A() }
Method_A() { Method_B().Wait() }
Task Method_B() { return T; }
There is no output using the Console.WriteLine in a IIS progress. If you want to output the result in a output window for the web project, you can use System.Diagnostics.Debug.WriteLine() method.

Resources