Typescript object property 'undefined' while it is not - angularjs

I'm farly new with Typescript and struggle with what seems to be a dumb issue:
I retrieve an 'agent' object from a service.
this.agentsController.getAgent(matricule).subscribe({
next: agent => {
console.log(agent)
console.log(agent.emailPro)
},
error: (error: string) => {
console.log(error)
}
});
According to the 1st console.log, it is well populated :
{
"agent": {
"matricule": "000001",
"nom": "DummyName",
"prenom": "DummyFirstname",
"emailPro": "dummy#dummy.fr",
"adresse1": "dummy address",
"telephonePerso": "0000000001"
}
}
But as clearly as the print of the agent shows a well defined email address (emailPro), the 2nd console.log always shows undefined
How is that possible ?
What am I missing ?

To summaries the comments chain as a valid response :
My service was encapsulating my proper agent object in some other dummy object that happens to be called 'agent' as well. Hence the confusion !
So instead of calling agent.EmailPro I should have called agent.agent.EmailPro.
I chose to fix my service instead so it parsed the API response better :
From this.httpClient.get('apiUrl').pipe(map((result:any) => result as Agent));
To this.httpClient.get('apiUrl').pipe(map((result:any) => result.agent as Agent));
Thanks again to #pietro909 & #T.J.Crowder

Related

Defining an Array in the fixtures and utilizing it in the main test case. Cypress Fixture throws a Type Error?

I am trying a test case with the help of the fixtures in Cypress. I have got the userdata.json folder under the ../cypress/fixtures folder.
When I try to run the test I always get this error TypeError Cannot read properties of undefined (reading 'assets')
Please find the code and other details here:
The .json file looks like this:
{
"email" : "****",
"password" : "****",
"title" : "dashboard",
"number" : "12",
"assets" : ["birthday-cake.jpg","cupcake.jpg","cake-black.jpg","building-1.jpg","building-2.jpg","cake-1.jpg","cake-2.jpg","cake-3.jpg","cake-4.jpg","car-1.jpg","car-2.jpg","car-3.png","longvideo.mp4","shortvideo.mp4","skyscrapper.jpg"]
}
My code looks like this :
/// <reference types="cypress" />
describe('Getting the names of the assets and iterating to find repeated names', ()=> {
before(function() {
cy.fixture('userdata').then(function(value){
this.value=value
})
})
it('login',function() {
cy.visit('https://sample-staging.com/login')
cy.url().should('include','staging')
cy.get('input[type="email"]').type(this.value.email).should('have.value',this.value.email)
cy.get('input[type="password"]').type(this.value.password).should('have.value',this.value.password)
cy.get('button').contains('Login').click()
cy.wait(5000)
cy.url().should('include',this.value.title)
})
it('Creating a new playlist', function() {
cy.get('.text-xfm').contains('PLAYLISTS').click()
cy.wait(5000)
cy.get('div.text-xfs').contains('Add New').click()
cy.get('label.text-xfx').should('contain','Playlist name is required')
cy.get('#playlistName').type('Test-Playlist').should('have.value','Test-Playlist')
cy.get('span.text-xfs').should('have.text','Choose assets to add to playlist').click()
cy.wait(5000)
cy.get('div.overflow-scroll').should('be.visible')
cy.log(this.value.assets)
this.value.assets.forEach(function(element) {
cy.selectAsset(element)
});
})
})
I have also created a custom command - selectAsset which is in the commands.json
I am not sure what I missed I tried all the answers that I have seen so far but always I get this error.
Find the screenshot here -
Test case passing
Throwing error
As it can be seen all the places where I use the fixture like email, password, title are all passing except the array - assets.
Help is much appreciated. Thanks in advance.
Instead of before you have to use beforeEach because cypress clears aliases between tests. So your first it block is able to access the fixture values where as the second one isn't.
From Cypress Docs
Under the hood, aliasing basic objects and primitives utilizes Mocha's
shared context object: that is, aliases are available as this.*.
Mocha automatically shares contexts for us across all applicable hooks
for each test. Additionally these aliases and properties are
automatically cleaned up after each test.
describe('Getting the names of the assets and iterating to find repeated names', () => {
beforeEach(function () {
cy.fixture('userdata').then(function (value) {
this.value = value
})
})
it('login', function () {
cy.visit('https://manager-staging.xogo.io/login')
cy.url().should('include', 'staging')
cy.get('input[type="email"]')
.type(this.value.email)
.should('have.value', this.value.email)
cy.get('input[type="password"]')
.type(this.value.password)
.should('have.value', this.value.password)
cy.get('button').contains('Login').click()
cy.wait(5000)
cy.url().should('include', this.value.title)
})
it('Creating a new playlist', function () {
cy.get('.text-xfm').contains('PLAYLISTS').click()
cy.wait(5000)
cy.get('div.text-xfs').contains('Add New').click()
cy.get('label.text-xfx').should('contain', 'Playlist name is required')
cy.get('#playlistName')
.type('Test-Playlist')
.should('have.value', 'Test-Playlist')
cy.get('span.text-xfs')
.should('have.text', 'Choose assets to add to playlist')
.click()
cy.wait(5000)
cy.get('div.overflow-scroll').should('be.visible')
cy.log(this.value.assets)
this.value.assets.forEach(function (element) {
cy.selectAsset(element)
})
})
})

React native async storage issues

In my react native app I am trying to save data into my local storage. It works fine most of the time but sometime I get error while setting the item.
So here is the code for me setting the item
async setString(key: string, value: any) {
try {
return await AsyncStorage.setItem(key, value)
} catch (e) {
LogService.logError(
'apiClient',
'apptype',
`Error setting local storage, key: ${key} error: ${JSON.stringify(e)}`,
)
}
}
One of the thing is that my error doesn't prints.
IOS users are having this issues
Do I need to first delete the item and then write to it? Doesn't setString override the value?
Is there any storage problem on the client?
Try using JSON.parse() when getting and JSON.stringify() when setting it
It's worked for me, you can try this.
useEffect(() => {
AsyncStorage.getItem('isLaunched').then((value) => {
AsyncStorage.setItem('isLaunched', 'true'); // No need to wait for `setItem` to finish, although you might want to handle errors
}); // Add some error handling, also you can simply do
}, []);

Firestore TypeError: collection().where() is not a function

I am trying to filter my docs in firebase firestore by checking if a doc 'users' array contains the user's email address. The 'chat' collection contains docs with ids: 'user#email.com:friend#email.com' and a doc contains messages and users stored in array.
I would like to list chats for the current user.
The problem is that every time I would like to use the where() clause I get to following error:
TypeError: firebase_app__WEBPACK_IMPORTED_MODULE_1___default.a.firestore(...).collection(...).where(...).onSnapshot(...).catch is not a function
This is my code:
firebase.firestore().collection("chats").where("users", "array-contains", currentUser.email)
.onSnapshot(async res => {
setChats(res.docs)
})
.catch(function (error) {
console.log("Error getting documents: ", error);
});
After read the "onSnapshot" method reference I understood it does not return anything. The method signature has a void return. You may have to pass the callback you want to be called as parameter of the onSnapshot method.
Actually you have an exemple in the Firestore documentation at the Handle listen errors section.
Bellow the snippet of code from the documentation:
db.collection("cities")
.onSnapshot(function(snapshot) {
// Handle changes
}, function(error) {
// Handle errors
});
I have same issue.I just not imported "where" method,couse when you click CTRL+space it is not showing for imports,and automatically it is not imports,I just written it by my hand.and it`s worked..

AppSync/Amplify Query using a Parameter Error ""Validation error of type FieldUndefined:"

I currently have a AppSync schema where I created a separate query within the AppSync console in order retain certain parameter (assetId) and get a list of the results in my DynamoDB table. I have tested the query already within the AppSync console and it works fine, I am now just having troubles using Amplify in my React App in order to call the query. I get the following error when running my App:
DisplayCard.js:34 Uncaught (in promise) {data: null, errors: Array(1)}
"Validation error of type FieldUndefined: Field 'getAssetIdRating' in type 'Query' is undefined # 'getAssetIdRating'"
I have tried following the documentation as per the Amplify site (https://aws-amplify.github.io/docs/js/api) but am still receiving this error.
For reference here is the query when I run it in the AppSync console: (returns the desired result)
query getAssetIdRating {
getRatingsAssetId(assetId:"949142fb-91d2-41bd-8c04-1d42ed8166c9") {
items {
id
assetId
rating
}
}
}
The resolver that I am using for this query is the following: (I have created a separate Index)
{
"version" : "2017-02-28",
"operation" : "Query",
"index": "assetId-index",
"query" : {
## Provide a query expression. **
"expression": "assetId = :assetId",
"expressionValues" : {
":assetId" : $util.dynamodb.toDynamoDBJson($ctx.args.assetId)
}
}
}
And now moving onto my React code, this is the current query that I am using within react, under src/graphql/queries.
export const getAssetIdRating = /* GraphQL */ `
query getRatingAssetId($assetId: ID) {
getAssetIdRating(assetId: $assetId) {
items {
id
assetId
rating
}
}
}
`;
And when I call it then in my React application:
componentDidMount = async () => {
this.getRatings();
}
getRatings = async () => {
let { assetIdRatings } = this.state;
const result = await API.graphql(graphqlOperation(queries.getAssetIdRating, {assetId: '949142fb-91d2-41bd-8c04-1d42ed8166c9'}));
console.log(result);
}
Note that when I call the listRatings query it works fine, just does not work with this query. And as a side note, I added this query later in manually through the AppSync console, I don't presume that should play an issue?
Either way, any help would be greatly appreciated! And I can upload anymore necessary code if required! Thanks for the help!
sorry you can ignore the question, it was a simple typing error :P You miss it when its late at night!
You can see the typing error on my Query:
getRatingsAssetId(assetId:"949142fb-91d2-41bd-8c04-1d42ed8166c9") {
getAssetIdRating(assetId: $assetId) {
Thanks though for the help!

Retrieving data from Firebase Realtime Database from React-redux app

I am trying to query data from my Firebase realtime database based on the child value matchID.
Below is the JSON export of my matchPredictions table with only one entry in it.
{
"-LP0aVMsmqfdHj7yfPnK" : {
"matchID" : "-LP0LKl_nR4VQf6Gxwz8",
"matchKickoff" : "2019-01-12T12:00",
"teamAName" : "Germany",
"teamAScore" : "2",
"teamBName" : "Denmark",
"teamBScore" : "3",
"userId" : "RZVbxcIB1SWxj0ohgJDqkEU9ia13"
}
}
I have the following function which gets called ..
export const fetchPredictionsForCompletedMatch = (match, token) => {
console.log("Match is " +match);
console.log("matchPredictionsFBRef is " + matchPredictionsFBRef);
const retrievePreds = matchPredictionsFBRef.orderByChild("matchID").equalTo(match).on("value",
function(snapshot){
console.log("Snapshot here is "+ snapshot);
});
return dispatch => {
retrievePreds.then(
response => dispatch(addMatchResultSuccess(match))
)
.catch(
err => dispatch(addMatchResultFail(err))
)
}
}
The value for match is -LP0LKl_nR4VQf6Gxwz8 as expected and matchPredictionsFBRef is https://projectOne.firebaseio.com/matchPredictions,
which is the table I am trying to query.
When this runs the error "The error is TypeError: retrievePreds.then is not a function" is thrown and snapshot is not printed to the console.
Any help would be much appreciated. Thanks.
Firebase's on() method can give results multiple times. Since a promise can only resolve once, the on() method can't return a promise.
If you only want to get a result once, use Firebase's once() method instead of on():
const retrievePreds = matchPredictionsFBRef.orderByChild("matchID").equalTo(match).once("value",
...
Can you call the function before chaining then.
retrievePreds().then()

Resources