Reading routing parameter in HTML - javascript

We can set the routing parameter through HTML:
<a [routerLink] = "['/api/foo/', id]"/>
I know that we can read routing parameter through handling event in the typescript:
import {OnInit, OnDestroy, Component} from '#angular/core';
#Component({...})
export class MyComponent implements OnInit{
constructor(private activatedRoute: ActivatedRoute) {}
ngOnInit() {
// subscribe to router event
this.activatedRoute.params.subscribe((params: Params) => {
let Id = params['id'];
console.log(Id);
});
}
}
However, is there any way to read route parameter in the HTML, not in the TypeScript component?
I would like to use in the following manner:
<a href="api/foo/[routerLink]"/>

If you want to get the param in html it is better to assign the param to a variable and use it in html
private param:number;
private ngOnInit() {
// subscribe to router event
this.activatedRoute.params.subscribe((params: Params) => {
this.param = params['id'];
console.log(this.param);
});
}
in your html
<div>{{param}}</div>

if you want to get id as number. You can use this.
id:number;
ngOnInit() {
this.subscription = this.activatedRoute.params.subscribe(
(params: any) => {
if (params.hasOwnProperty('id')) {
id= +params['id'];
//do whatever you want
}
}
);
}
and this destroyed the subscription
ngOnDestroy() {
this.subscription.unsubscribe();
}
and you can access the id field on html side.

Related

To get Id for edit functionality in angular

I have created a popup for edit functionality in my todo app and I need to get the id of the task for the purpose. using route is not giving a correct result. Is there any other way I can achieve it? I have given the code below.
this.id = this.route.snapshot.params['id'];
console.log(this.formData.value);
this.todoService.editTasks(this.id, this.formData.value).subscribe((res: any)=>{
console.log('update successful');
// this.router.navigateByUrl('/tasks');
})
}```
verfiy that you have the same id in the path of edit component :
{path: "edit/:id", component: someComponent}
use that in the component
import { ActivatedRoute } from '#angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit(){
//you need to unsubscribe in the ngOnDestroy
this.subscription = this.route.paramMap.subscribe(params=> {
//i use + to convert the id to a number type
let id =+params.get('id');
}
//To prevent memory leak
ngOnDestroy(): void {
if (this.subscription)
this.subscription.unsubscribe()
}
or use that :
ngOnInit(){
let id =this.route.snapshot.paramMap.get('id');
}
use the Angular doc : https://angular.io/tutorial/toh-pt5#extract-the-id-route-parameter
You need to use ActivatedRoute in order to get the id from the URL, check the following steps to use it.
// import
import { ActivatedRoute } from '#angular/router';
//dependency injection
constructor(private route: ActivatedRoute) { }
//implementation
ngOnInit() {
this.route.paramMap.subscribe(
params => {
this.id= params.get('id'); // This is the required Id
})
}
I hope this answers your question, Let me know if I got something wrong.

How to pass value of observable from a service to component to update the template

in the below code i am trying to display the value returned from observables. the observable function which returns the value is
created in a service as shown below in the code.
in the manin component, as shown below, i access that method from the service object and assign the supposed returned value to
a variable. that variable is linked to the template via interpolation as seen in the template section below.
the problem i am facing is, when i run the code, the value does not get passed from the service to the component and consequently
there is no change occure in the template
please let me know how to correct the code so the template gets updated with the right value from the observables in the service
component:
value: void;
constructor(private myservice: MyService1Service) {}
ngOnInit(){
this.todaydate2 = this.myservice.showTodayDate();
this.value = this.myservice.observablesTest();
}
service:
import { Injectable } from '#angular/core';
import { Router, ActivatedRoute, ParamMap } from '#angular/router';
import { Observable, Observer } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MyService1Service {
name : string;
obsValue: Observable<unknown>;
constructor(private route: ActivatedRoute) { }
ngOnInit(): void {
this.route.queryParams.subscribe(params => {
this.name = params['name'];
});
}
showTodayDate() {
let ndate = new Date();
return ndate;
}
observablesTest() {
this.obsValue = new Observable((observer) => {
console.log("Observable starts")
setTimeout(() => { observer.next("3000") }, 1000);
});
}
}
.html
<b>todayDate is: {{todaydate2}}</b>
<b>observableValue is: {{value}}</b>
note:
i tried
{{ value | async }}
but still nothing gets displayed in the html template
You aren't returning anything from the function in service.
observablesTest(): Observable<any> {
this.obsValue = new Observable((observer) => {
console.log("Observable starts")
setTimeout(() => {
observer.next("3000");
observer.complete();
}, 1000);
});
return this.obsValue; // <-- return here
}
And use async pipe in the component
<b>observableValue is: {{ value | async }}</b>

How to publish event from a component and receive it from another component in nativescript

How can I publish custom event from a component and receive it from another component in nativescript.
something like:
ComponentOne.ts
this.event.publish('someEvent', {name: 'a name'})
ComponentTwo.ts
this.event.subscribe('someEvent', (data) => {
const name = data.name;
})
You can use subject for this case
import { Injectable } from "#angular/core";
import { Subject } from "rxjs";
#Injectable()
export class MessageService {
private subject = new Subject<any>();
constructor() {}
sendMessage(message: any) {
this.subject.next(message);
}
getData() {
return this.subject.asObservable();
}
}
I defined 2 method here. The first method using next() to send message to the next subcriber. So in your component you just need to simply subscribe like this to get the data
private subscription$: Subscription;
public ngOnInit(): void {
this.subscription$ = this.messageervice
.getData()
.subscribe(data => { console.log(data); })
}
public ngOnDestroy(): void {
this.subscription$.unsubscribe();
}
Found a workaround.
the basic idea is to register a custom event on the root frame of the app and listen on it from the other components
ComponentOne.ts
frameModule.topmost().notify({
eventName: 'punched',
object: frameModule.topmost(),
})
ComponentTwo.ts
frameModule.topmost().on('punched', () => {
console.log('event received');
})

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

Reference to service from dynamically added component in Angular 6 CLI

I created a directive in Angular 6 named 'DeleteDirective' and reference to a service 'DeleteService' to make sure I can delete an item from my application. After the item is marked as deleted (in PHP back-end), I'll show an Undo element via the 'UndoComponent' that I dynamically added in the DeleteService. No problems so far.
#Directive({
selector: '[appDelete]'
})
export class DeleteDirective {
constructor(
#Inject(ViewContainerRef) viewContainerRef,
renderer: Renderer2
) {
service.renderer = renderer;
service.setRootViewContainerRef(viewContainerRef);
service.addUndoElement();
}
#HostListener('click') onClick() {
// (Some code to execute deletion)
this.deleteService.showUndoElement();
}
#Injectable({
providedIn: 'root'
})
export class DeleteService {
constructor(
rendererFactory: RendererFactory2,
private factoryResolver: ComponentFactoryResolver,
private appRef: ApplicationRef,
) {
this.renderer = rendererFactory.createRenderer(null, null);
this.factoryResolver = factoryResolver;
}
setRootViewContainerRef(viewContainerRef) {
this.rootViewContainer = viewContainerRef;
}
addUndoElement() {
const factory = this.factoryResolver.resolveComponentFactory(UndoComponent);
const component = factory.create(this.rootViewContainer);
// this.rootViewContainer.insert(component.hostView);
this.appRef.attachView(component.hostView);
const domElem = (component.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
document.body.appendChild(domElem);
}
}
Now, in the UndoComponent HTML I created a link to undo the action, named restoreItem. I would like to use another service named ListService to get some data again.
#Injectable()
export class UndoComponent implements OnInit {
constructor(private listService: ListService) {
}
restoreItem() {
this.currentList = this.listService.getSelectedList();
console.log(this.currentList); // null
}
}
It seems I cannot reference to the ListService (or any other service) from this dynamically added component to the DOM. It returns null. Any ideas how I can access a service from a dynamically added Component? Thanks so much for any directions!
Edit: added Listservice stub code for clarification
#Injectable({
providedIn: 'root'
})
export class ListService {
lists: List[];
list: List[];
currentList: List;
constructor(private http: HttpClient) { }
setSelectedList(list: List): void {
this.currentList = list;
}
getSelectedList(): List {
return this.currentList;
}
private handleError(error: HttpErrorResponse) {
console.log(error);
return throwError('Error! something went wrong.');
}
}
Are you setting the value of currentList in ListService in anyway.
setSelectedList in ListService is never called which is being used to set value of currentList. So currentList remains null.

Categories

Resources