Cookie Compliance Notification appearing on each website

I'm currently working on implementing a cookie consent feature using the component found at https://github.com/tinesoft/ngx-cookieconsent. The information does display on the site, but even after agreeing, it keeps reappearing upon refresh. I understand that I need to handle certain events, but I'm unsure of how to do so.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { NgcCookieConsentService } from 'ngx-cookieconsent';
import { Subscription }   from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, OnDestroy {

  //keeping references to subscriptions for later unsubscription
  private popupOpenSubscription: Subscription;
  private popupCloseSubscription: Subscription;
  private initializeSubscription: Subscription;
  private statusChangeSubscription: Subscription;
  private revokeChoiceSubscription: Subscription;

  constructor(private ccService: NgcCookieConsentService){}

  ngOnInit() {
    // subscribing to cookieconsent observables to react to key events
    this.popupOpenSubscription = this.ccService.popupOpen$.subscribe(
      () => {
        // you can use this.ccService.getConfig() to perform actions...
      });

    this.popupCloseSubscription = this.ccService.popupClose$.subscribe(
      () => {
        // you can use this.ccService.getConfig() to perform actions...
      });

    this.initializeSubscription = this.ccService.initialize$.subscribe(
      (event: NgcInitializeEvent) => {
        // you can use this.ccService.getConfig() to perform actions...
      });

    this.statusChangeSubscription = this.ccService.statusChange$.subscribe(
      (event: NgcStatusChangeEvent) => {
        // you can use this.ccService.getConfig() to perform actions...
      });

    this.revokeChoiceSubscription = this.ccService.revokeChoice$.subscribe(
      () => {
        // you can use this.ccService.getConfig() to perform actions...
      });
  }

  ngOnDestroy() {
    // unsubscribing from cookieconsent observables to avoid memory leaks
    this.popupOpenSubscription.unsubscribe();
    this.popupCloseSubscription.unsubscribe();
    this.initializeSubscription.unsubscribe();
    this.statusChangeSubscription.unsubscribe();
    this.revokeChoiceSubscription.unsubscribe();
  }
}

Answer №1

It appears that in your code snippet, the configuration is not being specified properly...

import { NgcCookieConsentService } from 'ngx-cookieconsent';

To ensure that cookies work correctly and to avoid annoying users, you must include the configuration and define a domain.

import {NgcCookieConsentModule, NgcCookieConsentConfig} from 'ngx-cookieconsent';

In this section, you set the domain:

const cookieConfig: NgcCookieConsentConfig = {
  cookie: {
    domain: 'example.com'
  },
  // ...

When importing NgcCookieConsentModule, remember to pass in the configuration like so:

NgcCookieConsentModule.forRoot(cookieConfig)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A guide on implementing a return function in Typescript with Knockout

Seeking assistance with translating a JavaScript function to Typescript, which involves the use of knockout objects as entry parameters. Here are the TypeScript imports I am utilizing: import $ = require("jquery"); import ko = require("knockout"); Belo ...

Guide to specifying an explicit return type annotation for a recursive closure with JSDoc

In a project that utilizes vanilla JavaScript and type checking with tsc through JSDoc annotations, I have encountered a challenging use case. There is a function that returns another function, which may recursively call itself while also reassigning certa ...

Angular error: The function redirectToLogin in src_app_app_routing_module__WEBPACK_IMPORTED_MODULE_0__.AppRoutingModule is not defined

I'm attempting to redirect users from the homepage to the login page using home.component.ts. Within this file, I've invoked a static method called "AppRoutingModule.redirectToLogin()" that I've defined in app-routing.module.ts by importing ...

Modifying the default FilterSettings in ejs-grid: A step-by-step guide

Brand new to Angular and Material technologies, I recently created a grid following the instructions provided here. Below is the html template for the table: <ejs-grid #grid [dataSource]='data' allowFiltering='true' allowPaging=& ...

Differentiating functions in Typescript through method overloading by inferring the second argument's type based on the first argument's

Looking to implement method overloading in Typescript with stricter type checking for method invocation based on different arguments. I am encountering an error: 'props' is possibly 'undefined'. This is the code that is causing the e ...

Minimize the occurrence of errors by focusing on parameter piping transformations in Angular

Recently, I created a custom transform pipe in order to condense a collection of objects. The implementation of the SumPipe looks like this: export class SumPipe implements PipeTransform { transform(items: ListCount[], attr: string): number { return ...

Setting up headers for HTTP requests in Angular2

I'm in need of customizing the authentication header for all API requests. I plan to include this header in the constructor and simply use this.http in my class methods. import { Injectable } from '@angular/core'; import { Config, Events } ...

TS2339 error message pops up on my screen: "Property 'chart' is not found on type 'Window'" - what could be the reason behind this?

I am encountering a warning when utilizing window.onload. Strangely, the warning disappears when I do not use it, but then my chart fails to display on screen. The issue crops up specifically when implementing chart.js, as the chart only shows up when wind ...

How to access custom parameters set in middleware in Next.js server actions?

I'm currently utilizing middleware.ts to intercept and authenticate user requests. However, I want to include data from our database in these authenticated requests. Within my server action code, the structure is as follows: export async function get ...

Using Svelte with Vite: Unable to import the Writable<T> interface for writable store in TypeScript

Within a Svelte project that was scaffolded using Vite, I am attempting to create a Svelte store in Typescript. However, I am encountering difficulties when trying to import the Writable<T> interface as shown in the code snippet below: import { Writa ...

Execute child function in Angular after parent completes operations on observables within a forEach loop

Within the parent component, I am collecting responses from observables in an array that is then passed to the child component. parent.component.ts let categoriesArray = []; for (let category of listing.categories) { this._projectService.getCatego ...

Tips for utilizing dispatch within a client class?

As I continue my journey of developing a client/wrapper using axios with Zod and Redux, I aim to create a client that can handle fetch errors and dispatch necessary state updates to Redux. After successfully implementing Zod and the validation part into t ...

Enhance Angular Forms: Style Readonly Fields in Grey and Validate Data Retrieval using Typescript

Is there a way to disable a form and make it greyed out, while still being able to access the values? https://i.sstatic.net/wt2c3.png 1/ Disabling controls with this.roleForm.controls['id'].disable() in Typescript does not allow me to retrieve ...

Customizing the datepicker to include additional values

After receiving a timestamp from the server, I am trying to update an input field with that date value. Even though the server sends the correct data, the input field remains empty without any errors appearing. private profileFormGroup = this.fb.group({ ...

Having trouble updating an array of objects using setState in Typescript

As a TypeScript novice, I am currently learning how to update the state of an array containing objects. The array in question is as follows: const [quantity, setQuantity] = React.useState<any[]>([ { id: '1', q: 100, }, ...

Tips for showing various tooltip text when iterating through a list?

I am currently working on a project where I am looping through a list and attempting to assign different tooltip text to various icons. However, I am struggling with the implementation. Here is a snippet of my code: <React.Fragment key={sv.key ...

When utilizing JavaScript syntax and performing API testing with Postman

Hello, I need some assistance from experts in connecting to Postman using the JavaScript code provided below. When running nodemon, the connection appears to be normal with no errors. Also, the GET request sent to Postman works fine. However, I am encounte ...

ngxs combined with Angular version 5.5

During my attempt to install and configure ngxs, I encountered several issues. Upon comparing my package.json file with the one provided on the ngxs GitHub master branch, I noticed that most of the installations were at version 6+. The error message I rece ...

Creating a Cordova application from the ground up, evaluating the options of using ngCordova, Ionic framework, and

With the goal of creating a multiplatform Cordova app for Android, iOS, and Windows, I have been exploring different approaches. My plan is to build an application with 4 or 5 features focused on service consumption (listing, adding, and editing items) wh ...

Exploring properties of nested elements in React

Picture a scenario where a specific element returns: <Component1> <Component2 name="It's my name"/> </Component1> Now, what I want to accomplish is something like this: <Component1 some_property={getComponent2'sN ...