how can i find paramter of previous route in angular - javascript

i want find the params in previous route in angular typescript .
i use this code :
private previousUrl: string = undefined;
private currentUrl: string = undefined;
constructor(private router: Router) {
this.currentUrl = this.router.url;
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.previousUrl = event.url;
this.currentUrl = this.currentUrl;
}
});
}
but i can not access to the params of this url :
http://localhost:4200/claims-manager/200/edit
i want ti access 200 . how can i find params in url ????

You can do it in your component file but It is a best practice to do it in a service (using rxjs) to pass data and call it in your component file
In your service
export class myService {
constructor() { }
private param = new BehaviorSubject("");
sharedParam = this.param.asObservable();
paramToPass(param:string) {
this.param.next(param)}
}
In your component class that set param
export class ComponentSetParam {
param: string
constructor(private myService: Service)
this.myService.setParam(this.param);
}
in your appModule
#NgModule({
declarations: [YourComponents]
imports: [ AppRoutingModule, YourModules...],
providers: [ShareService],
})
export class AppModule {}
Component that you want to pass data
export class ComponentGetParam {
paramFromService: string
constructor(private myService: Service) {
this.shareService.sharedData.subscribe(data : string => {
this.paramFromService = data;
})
}
}

Try this:
readonly _destroy$: ReplaySubject<boolean> = new ReplaySubject<boolean>(1);
constructor(
private activatedRoute: ActivatedRoute,
) {
this.activatedRoute.parent.paramMap
.pipe(
distinctUntilChanged(),
takeUntil(this._destroy$)
)
.subscribe((params: ParamMap) => {
const id = params.get('id');
});
}
ngOnDestroy() {
this._destroy$.next(true);
this._destroy$.complete();
}
Where 'id' is a name, that you use in the routing, e.g.
path: '/claims-manager/:id/'

Demo You can do it in service
import { Injectable } from '#angular/core';
import { BehaviorSubject } from 'rxjs';
#Injectable()
export class ShareService {
constructor() { }
private paramSource = new BehaviorSubject("");
sharedData = this.paramSource.asObservable();
setParam(param:string) { this.paramSource.next(param)}
}
in constructors
constructor(private shareService: ShareService)
in component in ngOnDestroy set this like this.shareService.setParam(param);
in appmodule
providers:[ShareService ]
in new component in ngOnInit or in constructor get like
this.shareService.sharedData.subscribe(data=> { console.log(data); })

Related

Ionic How to Pass variable to firebase equalTo method

I have already managed to fetch data form firebase.problem is when i'm going to filter data according to the id it doesn't work.
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
import { AngularFireDatabase, AngularFireList ,} from 'angularfire2/database';
import { Observable } from 'rxjs'
import { query } from '#angular/core/src/render3';
import { Key } from 'protractor';
class postview {
constructor(public title) { }
}
#Component({
selector: 'app-news-view',
templateUrl: './news-view.page.html',
styleUrls: ['./news-view.page.scss'],
})
export class NewsViewPage implements OnInit {
id: string;
public books: AngularFireList<postview[]>;
itemlol: Observable<any>;
posts: Observable<any[]>;
constructor(private route: ActivatedRoute , db: AngularFireDatabase) {
let idp :string = this.id;
this.posts = db.list('Posts' ,ref => {
return ref.orderByChild('Post_Id').equalTo(idp)
}).valueChanges();
// this.itemlol= db.object('Posts').valueChanges();
}
ngOnInit() {
this.id = this.route.snapshot.paramMap.get('id');
console.log(this.id);
console.log(this.posts);
}
}
in the section return ref.orderByChild('Post_Id').equalTo(idp) I need to pass variable in equalTo(). It should change according to the user instructions
Example
equalTo(01)
equalTo(02)
This is my firebase database:
The constructor is called before ngOnInit so the value for this.id will be undefined at the time of the query.
You should get the Parameters in the constructor
this.id = this.route.snapshot.paramMap.get('id');
let idp :string = this.id;
this.posts = db.list('Posts' ,ref => ref.orderByChild('Post_Id').equalTo(idp) ).valueChanges();

Confusing while Passing data between the components

I am new in angular 6, I am creating the project using angular 6. I am coming to the problem while sharing the data.
Here is my code:
1) Component Sidebar:
selectedCategory(type:any) {
this.loginService.categoryType = type; // need to pass this data
}
2) List Comp:
export class ListPostsComponent implements OnInit {
ngOnInit() {
// here I need the data
}
}
3) Service:
export class LoginService {
categoryType:any;
}
In your service make categoryType a Subject and call the next() when you need to pass data to another component:
#Injectable({
providedIn: 'root',
})
export class LoginService {
private categoryType: Subject<any> = new Subject<any>();
public categoryType$ = this.categoryType.asObservable();
public sendData(data: any){
this.categoryType.next(data);
}
}
Now in your Component Sidebar, you need to inject the service LoginService and call the sendData method:
constructor(private loginService: LoginService ){ }
selectedCategory(type:any) {
this.loginService.sendData(type);
}
Since a Subject is both an Observer and an Observable you can subscribe to the Subject and listen for changes in the component you wish to receive the data:
export class ListPostsComponent implements OnInit {
constructor(private loginService: LoginService ){ }
ngOnInit() {
this.loginService.categoryType$.subscribe((data) => {
//use your data here
});
}
}
Here is a working example of the above solution in Stackblitz: https://stackblitz.com/edit/angular-2sld4k?file=src%2Fapp%2Floginservice.service.ts

share data from service to component after render the function in angular 4

i have service, in service, I have a "cohortTabsResult" method whitch sets the charts array. i want to use this arry in "chart.component"
export class CohortService {
public charts: Array<any>;
cohortTabsResult(obj){
this.charts = []
const subscription = this.cohortDataReq(obj).subscribe(res => {
if(res.status !== 500){
const dataObj = {
definedChart: obj.graph_type,
definedChartData: []
};
this.charts.push(dataObj);
const response = res.json()
//console.log(response)
if (response.error) {
//this.isLoaded = false;
}
else{
Array.prototype.forEach.call(response.data, dataRes => {
const newData = this.getChartDataFormat(dataRes, obj.graph_type, "userType")
dataObj.definedChartData = _.cloneDeep(newData);
});
}
}
});
}
}
and this is my chart.component here I am getting the empty array.
export class ChartCohortComponent implements OnInit{
charts: any;
constructor(private cohortService: CohortService, private route:
Router, public activatedRoute: ActivatedRoute) {
this.charts = this.cohortService.charts;
}
ngOnInit(){
console.log("ch", this.charts)
}
}
import CohortService to your component, add it to the providers in #component, now you can access the variables inside the service. :D
import { CohortService } from '../../cohort.services'; // whatever the path is..
#Component({
selector: '',
templateUrl: '',
styleUrls: [''],
providers: [CohortService]
})
export class ChartCohortComponent implements OnInit{
charts: any;
constructor(private cohortService: CohortService, private route:
Router, public activatedRoute: ActivatedRoute) {
this.charts = this.cohortService.charts;
}
ngOnInit(){
console.log("ch", this.charts)
}
}

Angular router get child param from root component

I have this structure in my app.component.html:
<app-main-nav></app-main-nav>
<router-outlet></router-outlet>
This is my routes:
const routes = [
{path: "", redirectTo: "home", pathMatch: "full"},
{
path: "posts", component: PostsComponent,
children: [{
path: ":id",
component: PostComponent
}];
}
]
I am trying to access the params from the PostComponent page in my MaiNavComponent but it throws an error.
export class MainNavComponent implements OnInit {
constructor( private route: ActivatedRoute) {
route.params.subscribe(console.log)
}
}
How can I get the :id of the PostComponent from the MainNavComponent?
I tried to do this:
route.params.subscribe(console.log)
Here I get an empty object.
And this:
route.firstChild.params.subscribe(console.log)
Cannot read property 'params' of null
The problem is that ActivatedRoute only available inside components loaded in an outlet (route-outlet). In the outer components you can inject the router and use it as follow:
export class MainNavComponent implements OnInit {
constructor(private router: Router) {}
ngOnInit() {
// Fires when the url changes
this.router.events.subscribe(data => {
// Only handle final active route
if (data instanceof NavigationEnd) {
// parsedUrl conatins params, queryParams
// and fragments for the active route
let parsedUrl = this.router.parseUrl(this.router.url);
console.log(parsedUrl);
}
});
}
}
I hope this will help you.
constructor(
private router: Router,
private activatedRoute: ActivatedRoute) {
}
ngOnInit() {
this.loadParams();
}
private loadParams(): void {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
let activatedRoute = this.activatedRoute.firstChild;
while (!activatedRoute) {
activatedRoute = activatedRoute.firstChild;
}
const value = activatedRoute.snapshot.paramMap.get('parmeter key');
}
});
}
You have to snapshot to get ID from the URL.Uodate constructor with below
constructor( private route: ActivatedRoute) {
}
ngOnInit() {
// (+) converts string 'id' to a number
let id = +this.route.snapshot.params['id'];
}

Angular2: Send data from one component to other and act with the data

I'm learning Angular2. In order to that, I have 2 components, on the click of one of the components, the other component should be notified and act with that.
This is my code so far:
export class JsonTextInput {
#Output() renderNewJson: EventEmitter<Object> = new EventEmitter()
json: string = '';
process () {
this.renderNewJson.next(this.json)
}
}
The process function is being called on the click on the first component.
On the second component I have this code:
export class JsonRendered {
#Input() jsonObject: Object
ngOnChanges () {
console.log(1)
console.log(this.jsonObject)
}
}
The ngOnChanges is never runned, I dont get how to pass the info from one component to other
EDIT
There is an app component which is parent of those 2 components. None of both is parent of the other
This is how my clasess look now:
export class JsonRendered {
private jsonObject: Object
constructor (private jsonChangeService: JsonChangeService) {
this.jsonChangeService = jsonChangeService
this.jsonObject = jsonChangeService.jsonObject
jsonChangeService.stateChange.subscribe(json => { this.jsonObject = json; console.log('Change made!') })
}
}
export class JsonTextInput {
json: string = '';
constructor (private jsonChangeService: JsonChangeService) {
this.jsonChangeService = jsonChangeService
}
process () {
this.jsonChangeService.jsonChange(this.json)
}
}
And the service
import {Injectable, EventEmitter} from '#angular/core';
#Injectable()
export default class JsonChangeService {
public jsonObject: Object;
stateChange: EventEmitter<Object> = new EventEmitter<Object>();
constructor(){
this.jsonObject = {};
}
jsonChange(obj) {
console.log('sending', obj)
this.jsonObject = obj
this.stateChange.next(this.jsonObject)
}
}
Create a service like so...
import {Injectable, EventEmitter} from 'angular2/core';
#Injectable()
export class MyService {
private searchParams: string[];
stateChange: EventEmitter<any> = new EventEmitter<any>();
constructor(){
this.searchParams = [{}];
}
change(value) {
this.searchParams = value;
this.stateChange.next(this.searchParams);
}
}
Then in your component...
import {Component} from 'angular2/core';
import {MyService} from './myService';
#Component({
selector: 'my-directive',
pipes: [keyValueFilterPipe],
templateUrl: "./src/someTemplate.html",
providers: [MyService]
})
export class MyDirective {
public searchParams: string[];
constructor(private myService: MyService) {
this.myService = myService;
myService.stateChange.subscribe(value => { this.searchParams = value; console.log('Change made!') })
}
change(){
this.myService.change(this.searchParams);
}
}
You have to subscribe to the eventemitter, then update your variable. The change event in the service would get fired of from something like...
(click)="change()"

Categories

Resources