Dynamically importing modules into a angular2 app - ajax

Assuming the scenario where there are two angular 2 apps each with a Java developed back-end (app-1 and app-2) deployed in different packages.
Is it possible to make a ajax call from app 1 and based on the data retrieved by that ajax call to load into app 1 modules from app 2 using a Ajax call or something?
If yes, how would that work?
Example:
import { Component, OnInit } from '#angular/core';
import { AppService } from './shared/app.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AppService]
})
export class AppComponent{
constructor(private appService: AppService){}
ngOnInit(){
let test = this.appService.checkUserPrivileges();
if(test.length > 1){
// make ajax calls that retrieves modules based on the test data
// inject ajax retrieved modules into module that contains the component somehow
}
}
}

Related

Is there a specific way of using nativescript-videorecorder plugin to work with angular?

I am unable to get the nativescript-videorecorder to work in my app.
I had installed the plugin and used the code given on the github https://github.com/triniwiz/nativescript-videorecorder for typescript. I created a simple HTML ui and tried to call a function to open the camera to record video. However it is does not work
For app.component.html i used the tag <Image src="videoCam" (tap)="onCam()">
For app.component.ts i used the below code
import { VideoRecorder, Options as VideoRecorderOptions } from 'nativescript-videorecorder';
#Component({
moduleId: module.id,
selector: "ns-app",
templateUrl: "app.component.html"
})
export class AppComponent {
export class AppComponent {
onCam() {
const options: VideoRecorderOptions = {
hd: true
saveToGallery: true
};
const videorecorder = new VideoRecorder(options);
videorecorder.record().then((data) => {
console.log(data.file)
}).catch((err) => {
console.log(err)
});
}
}
Is there anything i am missing to get this to work ?

handling link opening event in HtmlView

I have a html code that has a link inside it. code below is my template:
<HtmlView [html]="htmlString" ></HtmlView>
this is my component:
import { Component } from "#angular/core";
#Component({
moduleId: module.id,
templateUrl: "./creating-htmlview.component.html"
})
export class CreatingHtmlViewExampleComponent {
public htmlString: string;
constructor() {
this.htmlString = 'google';
}
}
how to handle a element inside of HtmlView when it run ? there is a way to detect when user run the link?
That's not supported yet, there is an open feature request. You may write a plugin that implements native apis like ClickableSpan or Linkify.

Nativescript update http response when app launches

I have an app I have inherited that is getting data from an API endpoint. We have found that when we change data on the API, the changes are not reflected in the app. If we uninstall and re-install the app on a mobile device, then the new data from the API is displayed. Here is an example of the Building Detail page:
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from "#angular/router";
import { switchMap } from 'rxjs/operators';
import { Building } from "../shared/building/building";
import { HttpService } from "../services/http/http.service";
import {
getString,
setString
} from "application-settings";
#Component({
moduleId: module.id,
selector: 'building-detail',
templateUrl: 'building-detail.component.html',
styleUrls: ["./building-detail-common.css"],
providers: [ Building, HttpService ]
})
export class BuildingDetailComponent implements OnInit {
paramName: string;
constructor(
private route: ActivatedRoute,
public building: Building,
private httpService: HttpService) {
this.route.params.subscribe(
(params) => {
this.paramName = params['name']
}
);
}
ngOnInit() {
console.log("ON INIT FIRED " + this.paramName);
let buildingInfo = JSON.parse(getString("buildingInfo"));
for (let item of buildingInfo) {
if (item.attributes.title === this.paramName) {
this.building.name = item.attributes.title;
this.building.desc = item.attributes.body.value;
let imageEndpoint = "file/file/" + item.relationships.field_building_image.data.id;
let imageUrl = this.httpService.getData(imageEndpoint)
.subscribe(data => {
this.building.image = "https://nav.abtech.edu" + data['data'].attributes.url;
console.log("The building image URL is " + this.building.image);
}, (error) => {
console.log("Error is " + error);
});
}
}
}
}
I am happy to share other files/code if you would like to look at those. Thanks!
The reason your data is not being updated is not because the ngOnInit is not being executed, it's because you're caching the old value and reloading it each time the app is run. You're caching the data persistently across app runs with appSettings and that's why you are seeing the values stay the same until you uninstall.
If you don't want to show a cached value then don't read from the app settings, or at least don't read from appSettings until you've refreshed the data once.
ngOnInit is something that is executed only when your component is created, it will never be executed again.
Also there is difference between app launch and resume, if you want to update data every time when user opens the app, you should listen to resume event and perform apis calls inside ngZone
You may even use push notification / data message if you want to notify user immediately when data changes on backend

Update Angular app data in real time using websocket

I have API written in Spring on server side also managed websocket code that opens socket and continuously responds with some data (for example /getlikes returns number of likes).
How do I call this API in service that continuously checks for updated values (I don't want to use any time interval for service call)?
you can use sockjs-client and do somethjing like this.
import { Component } from '#angular/core';
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
private serverUrl = 'http://localhost:8080/socket'
private title = 'WebSockets chat';
private stompClient;
constructor(){
this.initializeWebSocketConnection();
}
public initializeWebSocketConnection(){
let ws = new SockJS(this.serverUrl);
this.stompClient = Stomp.over(ws);
let that = this;
this.stompClient.connect({}, function(frame) {
that.stompClient.subscribe("/chat", (message) => {
if(message.body) {
$(".chat").append("<div class='message'>"+message.body+"</div>")
console.log(message.body);
}
});
});
}
public sendMessage(message){
this.stompClient.send("/app/send/message" , {}, message);
$('#input').val('');
}
}
you can find a full tutorial on this in this article
#Bhagvat Lande
I think you are looking for this :
https://angular.io/guide/observables
getting live data from server continuosly and refelect changes in html in angular2

ngOnInit doesn't run until after I navigate to another component

In my NativeScript app, I have the route set up as
export const routes = [
{ path: "", component: AppComponent},
{ path: "home", component: HomeComponent},
{ path: "login", component: LoginComponent},
{ path: "news" , component: NewsComponent}
];
After a user is logged in through firebase the user is auto redirected to the HomeComponent. I should mention that I have a user service that gets fired from the AppComponent Constuctor that determines if a user is already logged in then redirects them to login or home.
I have console.log() spread across the component to see when things gets triggered so I can try to figure out where to place the code.
import {Component, OnInit} from "#angular/core";
import {Page} from "ui/page";
import {RouterExtensions} from 'nativescript-angular/router';
import firebase = require("nativescript-plugin-firebase");
#Component ({
selector : "home",
templateUrl: "./pages/home/home.html",
styleUrls: ["./pages/home/home.css"]
})
export class HomeComponent implements OnInit {
private router;
constructor(page: Page, router: RouterExtensions) {
console.log("HOME CONSTRUCTOR TRIGGERED");
page.actionBarHidden = false;
this.router = router;
}
ngOnInit(){
console.log("HOME NGONIT TRIGGERED");
}
goToNews(){
this.router.navigate(["/news"]);
}
}
In home.html I have a button that triggers goToNews(). When I load up the app, I can see in my console when HomeComponent constructor gets triggered, but I never see ngOnInit get triggered. The strange thing is that when I click on the button to navigate to /news, this is when I see the HomeComponent ngOnInit fire in my console. Is this the way it's suppose to work?
This all comes down to a "big picture understanding" where I'm trying to figure out the best place to put my logic down when HomeComponent gets loaded. I read that putting it in the constructor was a bad idea and having it in ngOnInit is ideal however I don't see how this can make any sense if ngOnInit only gets triggered after I try to navigate away from the component.
Please help me understand this.
UPDATE: I added a console.log to ngOnInit in AppComponent and this does get fired when the app first loads. So it must be the navigation in the services that is causing ngOnInit to not fire in HomeComponent.
Try putting the router.navigate() into a separate "Zone":
import:
import { NgZone } from "#angular/core";
inject:
constructor(private zone: NgZone) { ... }
apply:
this.zone.run(() => {
this.router.navigate(["/news"]);
});
found here.

Resources