IntersectionObserver is not defined error on server side. Intersection Observer with angular universal(Server side rendering) - angular8

I have an angular Universal application(server-side rendering).
I am using IntersectionObserver for lazy loading images and it is working fine. Although it is giving me this error on server-side logs (pm2 server-error.log).
ERROR ReferenceError: IntersectionObserver is not defined
at LazyLoadDirective.lazyLoadImage (/home/ubuntu/dist/server/main.js:13160:21)
at LazyLoadDirective.ngAfterViewInit (/home/ubuntu/dist/server/main.js:13154:33)
at callProviderLifecycles (/home/ubuntu/dist/server/main.js:52384:18)
at callElementProvidersLifecycles (/home/ubuntu/dist/server/main.js:52349:13)
at callLifecycleHooksChildrenFirst (/home/ubuntu/dist/server/main.js:52331:29)
at checkAndUpdateView (/home/ubuntu/dist/server/main.js:63214:5)
at callViewAction (/home/ubuntu/dist/server/main.js:63570:21)
at execComponentViewsAction (/home/ubuntu/dist/server/main.js:63498:13)
at checkAndUpdateView (/home/ubuntu/dist/server/main.js:63211:5)
at callViewAction (/home/ubuntu/dist/server/main.js:63570:21)
which I understand is because IntersectionObserver is client side thing since it operates on DOM elements.
But It is kind of annoying to see the above error on the server side so I wanted to correct the issue for that I took the help of isPlateformBrowser function by injecting PLATEFORM_ID into my lazyload directive. It is still working fine for me and I am not seeing any server-side error logs for this.
This is my LazyLoadDirective code
export class LazyLoadDirective implements AfterViewInit{
#HostBinding('attr.src') srcAtr = null;
#Input() src: string;
constructor(private el: ElementRef, #Inject(PLATFORM_ID) private plateformId : Object) {}
//putting check for isplateformbrowser.
ngAfterViewInit(){
if(isPlatformBrowser(this.plateformId)){
this.canLazyLoad ? this.lazyLoadImage() : this.loadImage();
}
}
private canLazyLoad(){
return window && 'IntersectionObserver' in window;
}
private lazyLoadImage(){
const obs = new IntersectionObserver(entries =>{
entries.forEach(({ isIntersecting })=>{
console.log("intersecting value isIntersecting",isIntersecting);
if(isIntersecting){
this.loadImage();
obs.unobserve(this.el.nativeElement);
}
});
});
obs.observe(this.el.nativeElement);
}
private loadImage(){
this.srcAtr = this.src;
}
}
Since this is something new for me, It would be really helpful for me if someone could suggest a better solution for this problem, Also I have seen some post on a different platform that IntersectionObserver is not reliable. Please help me understand the scenarios where this could cause trouble, any link to a blog post or any kind of help is enough for me.
Thank you.

Awesome!!! I added a '#HostBinding('class') elementVisibilityClass: string' onto that directive to add a CSS class on the targeted element depending on the visibility status.
#HostBinding('class') elementVisibilityClass: string;
...
private _callback = (entries: any) => {
entries.forEach((entry: any) => {
this.elementVisibilityClass = entry.isIntersecting ? 'visible' : 'hidden';
});
}

Related

vuex-persistedstate not saving class methods

I'd like to preference this by saying my backgrounds in in C# so I like declaring methods within my classes. I've created a user class that contains properties and methods and I've added this to my vuex-persistedstate. One of the methods is a logout() method which clears out the properties. When I tried to invoke this method I got the following error:
TypeError: this.$data.user.logout is not a function
I then reviewed local storage and noted the user did not have reference to the class method. So I went ahead and copied the logic from the method into my vue component and it worked so I'm assuming the issue is vuex-persistedstate does not save references to methods which is why the method call did not work.
I'd like to declare the logout method in one location rather than spreading it out across vue components, what is the best practice for accomplishing this? Is it possible to do this in the class declaration or do I need a user helper file?
Sure Berco! My code is also up on GitHub so you can review it there too, but basically it seems to me that vuex does not store methods. The first file you should review is my user.js file:
https://github.com/Joseph-Anthony-King/SudokuCollective/blob/master/SudokuCollective.WebApi/client/src/models/user.js
In this file I have a method called shallow clone which takes the info received from the API and assigns it to the user:
shallowClone(data) {
if (data !== undefined) {
this.id = data.id;
this.userName = data.userName;
this.firstName = data.firstName;
this.lastName = data.lastName;
this.nickName = data.nickName;
this.fullName = data.fullName;
this.email = data.email;
this.isActive = data.isActive;
this.isAdmin = data.isAdmin
this.isSuperUser = data.isSuperUser;
this.dateCreated = data.dateCreated;
this.dateUpdated = data.dateUpdated;
this.isLoggedIn = data.isLoggedIn;
}
}
You of course don't need to abstract this away but I've found it makes the code easier to maintain.
Then in the mounted() lifecycle hook I assign the user received from the API to the component user via the shallowClone method. Please bear in mind I've done additional work on this project and the login form is now it's own component which receives the user as a prop from the app:
https://github.com/Joseph-Anthony-King/SudokuCollective/blob/master/SudokuCollective.WebApi/client/src/components/LoginForm.vue
mounted() {
let self = this;
window.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
self.authenticate();
}
});
this.$data.user = new User();
this.$data.user.shallowClone(this.$props.userForAuthentication);
},
The full code can be reviewed here:
https://github.com/Joseph-Anthony-King/SudokuCollective
I found a solution... I'm working on improving it. Basically I use the values pulled from localstorage into vuex to create a new user object in the vue component that has reference to the methods located in my user class declaration. I recalled recommendations that we should create clones of objects pulled from vuex for use within the vue component. I'm still refining the code but that's basic idea.

If method returns data then load in module(view) - Aurelia

Forgive me for my ignorance but I've just started out with Aurelia/ES6 and a lot baffles me at the moment. I'm completely new to client side frameworks, so hopefully what I'm trying to achieve is possible within the framework.
So as the title indicates I'm fetching data within a class:
import {inject} from "aurelia-framework";
import {HttpClient} from "aurelia-http-client";
let baseUrl = "/FormDesigner/";
#inject(HttpClient)
export class FormData{
constructor(httpClient)
{
this.http = httpClient;
}
GetFormById(formId)
{
return this.http.get(`${baseUrl}/GetFormById/${formId}`)
.then(resp => resp.content);
};
}
Now I can see/receive the data which is great but after digging into the docs I cannot seem to figure out:
Load a separate related module/view by Id into the main view (app.html)
If no data, error and no Id passed then redirect to no-form view
Scenario:
User A navigates to "FormDesigner/#/form/3E7689F1-64F8-A5DA0099D992" at that point "A" lands on the form page, now if successful and data has been returned pass the formId into a different method elsewhere and then load in a module/view - Pages, possibly using <compose></compose>
This is probably really simple but the documentation (in my opinion) seems rather limited to someone that's new.
Really appreciate any guidance/high level concepts, as always, always much appreciated!
Regards,
Sounds like you might want to just partake in the routing lifecycle
If you are navigating to a module you can create an activate method on the view model which will be called when routing starts.
In this method you can return a promise (while you fetch data) and redirect if the fetch fails
In fact if the promise is rejected, the routing will be cancelled
If successful you can use whatever method you need to load in your module (assuming it can't just be part of the module that is being loaded since routing won't be cancelled)
Something like
activate(args, config) {
this.http.get(URL).then(resp => {
if (resp.isOk) {
// Do stuff
} else {
// Redirect
}
});
}

Aurelia: how to manage sessions

I'm trying to develop a website where the nav-bar items depend on the role of the user who is logged in.
As Patrick Walter suggested on his blog, I was thinking to create a session.js file where I would store information about the current user: their username and role. I would then inject this file in nav-bar.js and create a filter for the routes, for which the user does not have access to. Everything worked fine until I hit the refresh button... In fact, it creates a new session object and I loose all the information store in the previous one.
I have seen in the docs the singleton method, but I'm not sure how to use it. If I insert it in my code such as below, I get the message: aurelia.use.singleton is not a function.
import config from './auth-config';
export function configure(aurelia) {
console.log('Hello from animation-main config');
aurelia.use
.singleton(Session)
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-animator-css')
.plugin('paulvanbladel/aurelia-auth', (baseConfig) => {
baseConfig.configure(config);
});
aurelia.start().then(a => a.setRoot());
}
export class Session {
username = '';
role = '';
reset() {
console.log('Resetting session');
this.username = '';
this.role = '';
};
}
My last idea would be to encrypt the role/username and use the browser's session to store the information. But I wanted to ask to more experienced developers their opinion about the topic.
Thanks for your help!
EDIT: Here is my code for session.js
export class Session {
username = '';
role = '';
reset() {
console.log('Resetting session');
this.username = '';
this.role = '';
};
}
And this is how I inject it:
import {Session} from './services/session';
#inject(Session)
export class RoleFilterValueConverter {
constructor(session) {
console.log('Hello from RoleFilter constructor', session)
this.session = session;
};
toView(routes, role) {
console.log('Hello from view', role, this.session)
if (this.session.role == 'Superuser')
return routes;
return routes.filter(r => {
var res = !r.config.role || (r.config.role == this.session.role);
return res
});
}
}
In the main entry point (let's assume it's index.html) you should have something like this:
<body aurelia-app="path/to/main">
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<script>
System.import('aurelia-bootstrapper');
</script>
</body>
This imports the entire aurelia enviorment and so when it reaches the export function configure(aurelia) { ... } it should pass an instance of type Aurelia and bind it to the aurelia parameter and should resolve your aurelia.use.singleton is not a function. error. After that, in your session.js file when using #inject(Session) it should pass the same instance you declared at startup.
I also implemented a singleton session object to store user data and have chosen this method because it's more convenient to rely on dependency injection rather than always calling a method to get user data from a cookie.
Though Laurentiu's answer is not bad, there are better ways to handle this that do not add complexity to your app.
You do not need to need to specify this as a singleton. This particular function is more for an edge case where you would want to expose a particular item to the dependency injection container as a singleton before startup.
In fact, the Aurelia dependency injection framework treats all modules as singletons unless specified otherwise. Thus, the code should work as you have it written there, without the configure function.
I've written up an in-depth blog that you maay find helpful here: http://davismj.me/blog/aurelia-auth-pt2/

Understanding cakephp3 error handling

I want to create a maintenance Page for my cake website by checking a Database Table for a maintenance flag using a sub-function of my AppController "initilize()" method. If the flag is set, i throw my custom MaintenanceException(Currently containing nothing special):
class MaintenanceException extends Exception{
}
To handle it, I implemented a custom App Exception Renderer:
class AppExceptionRenderer extends ExceptionRenderer {
public function maintenance($error)
{
return "MAINTENANCE";
}
}
I am able to see this maintenance Text on my website if I set my DB flag to true, but I could not find any information in cake's error handling documentation (http://book.cakephp.org/3.0/en/development/errors.html) on how I can actually tell the Exception renderer to render view "maintenance" with Template "infopage".
Can I even us that function using the ExceptionRenderer without a custom error controller? And If not, how should a proper ErrorController implementation look like? I already tried this:
class AppExceptionRenderer extends ExceptionRenderer {
protected function _getController(){
return new ErrorController();
}
public function maintenance($error)
{
return $this->_getController()->maintenanceAction();
}
}
together with:
class ErrorController extends Controller {
public function __construct($request = null, $response = null) {
parent::__construct($request, $response);
if (count(Router::extensions()) &&
!isset($this->RequestHandler)
) {
$this->loadComponent('RequestHandler');
}
$eventManager = $this->eventManager();
if (isset($this->Auth)) {
$eventManager->detach($this->Auth);
}
if (isset($this->Security)) {
$eventManager->detach($this->Security);
}
$this->viewPath = 'Error';
}
public function maintenanceAction(){
return $this->render('maintenance','infopage');
}
}
But this only throws NullPointerExceptions and a fatal error. I am really dissapointed by the cake manual as well, because the code examples there are nowhere close to give me an impression of how anything could be done and what functionality I actually have.
Because I had some more time today, I spent an hour digging into the cake Source and found a solution that works well for me (and is propably the way it should be done, altough the cake documentation does not really give a hint):
Step 1: Override the _template(...)-Method of the ExceptionRenderer in your own class. In my case, I copied the Method of the parent and added the following Code at the beginning of the method:
$isMaintenanceException = $exception instanceof MaintenanceException;
if($isMaintenanceException){
$template = 'maintenance';
return $this->template = $template;
}
This tells our Renderer, that the error Template called "maintentance"(which should be located in Folder: /Error) is the Error Page content it should render.
Step 2: The only thing we have to do now (And its is kinda hacky in my opinion, but proposed by the cake documentation in this exact way) is to set the layout param in our template to the name of the base layout we want to render with. So just add the following code on top of your error template:
$this->layout = "infopage";
The error controller I created is actually not even needed with this approach, and I still don't know how the cake error controller actually works. maybe I will dig into this if I have more time, but for the moment.

I am getting a $save() not a function in Angular

I am trying to build a relatively simple web application following tutorials from the book ProAngular. The book examples work fine, but when I try and build my own app, I am getting stuck on a strange error. Here is part of my code:
$scope.dispositionsResource = $resource(dispositionUrl + ":id", { id: "#id" },
{ create: {method: "POST"}, save: {method: "PUT"}, delete: {method: "DELETE"}
});
. . .
$scope.updateDisposition = function (disposition) {
alert("DISPOSITION: "+disposition.name);
disposition.$save();
}
The Create and Delete functions work fine. The updateDisposition method is being called form an HTML form and the correct disposition value is being passed (based on the Alert). But the error I am getting is:
"Error: disposition.$save is not a function"
None of my example code separately defines a save function, the function should be part of the restful service ($resource). Shouldn't it?
Any pointers in the right direction would be greatly appreciated.
Ted
I did end up getting this working. Not totally sure why, but I renamed the Save function to 'Update' and associated it with the PUT functionality.
$scope.dispositionsResource = $resource(dispositionUrl+":id", { id: "#id" },
{ 'create': {method: "POST"}, 'update': {method: "PUT"}
});
$scope.updateDisposition = function (disposition) {
$scope.dispositionsResource.update(disposition);
$scope.editedDisposition = null;
}
calling update rather than save worked. Something seemed to be interfering with using the term 'save'. Like I said, not sure what . . . yet. One of those head-scratchers for me. Thanks to those who tried to assist!
I am learning angular myself, but the first problem I can see with your code is that it doesn't look like you are defining $resource correctly ( fair warning, Angular has a ton of caveats and you may simply be delving into one I am not aware of).
I believe a more straight forward way of doing what you are trying to do is first creating an angular factory for the $resource, like so:
angular.module('yourModuleName')
.factory('disposition', function($resource) {
return $resource('/whatever/url/youwant/:id', {
id: '#id'
})
});
And then from there, declare the factory as a dependency for your controller:
angular.module('yourModuleName')
.controller('yourControllerName', function($scope, disposition) {
$scope.submitForm = function($scope)
disposition.save($scope.nameOfYourModel);
});
One thing to keep in mind is that $resource has all of the methods that you declared by default. From the docs at https://docs.angularjs.org/api/ngResource/service/$resource these are what are available out of the box:
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
Personally, I prefer to use the $http service myself. Yes, it is quite a bit more verbose than using $resource but I feel that it is much easier to understand $http when starting with angular than the $resource service. To save yourself from a world of headaches in the future, I highly recommend becoming familiar with the concept of promises in Angular as many of its services make use of them.
Good luck.