Google plus comment box integration with Angular2 app - javascript

I was trying to integrate google plus comment box into my MEAN 2.0 website by following this link. I configured few things as per angular2 way but not sure if that is the correct way to do that. Please guide me to integrate it as not much help i found on internet for this.
index.html
added below link to index.html
<script src="https://apis.google.com/js/plusone.js"></script>
app.ts
declare let gapi:any;
#Component({
selector: 'blogComment',
template: `
<div class="g-commentcount" data-href="blog/"></div>
<div id="{{commentId}}"></div>
`
})
export class CommentComponent /*implements OnInit */{
commentId : string = "comments";
constructor() {
console.log("CommentComponent const");
this.embedComment();
}
/*ngOnInit(){
}*/
embedComment() {
gapi.comments.render(this.commentId, {
href: window.location,
width: '624',
first_party_property: 'BLOGGER',
view_type: 'FILTERED_POSTMOD'
});
}
}
Here is another component in the same app.ts file which is mapped to "blc" router.
#Component({
providers: [CommentComponent],
template : `
<blogComment></blogComment>
`
})
export class BlogComponent{
constructor(public comment: CommentComponent) {
console.log("BlogComponent const");
}
}
Router configuration
const appRoutes: Routes = [
...
{ path: 'blc', component: BlogComponent },
];
const appRoutingProviders: any[] = [
];
const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
and finally included everything in NgModule like below.
let declarationArr : Array<any>= [
BlogHomeComponent, ckeditorClass, AuthApp,
BlogNotFoundComponent, BlogComponent, BlogListComponent,
NewBlogComponent, CommentComponent
];
#NgModule({
imports: [ BrowserModule, HttpModule, CKEditorModule, FormsModule, routing ],
declarations: declarationArr,
providers: [ appRoutingProviders ],
bootstrap: [ BlogHomeComponent ]
})
export class app{}
const platform = platformBrowserDynamic();
platform.bootstrapModule(app);
but the comment box is not at all loading into the browser.
UPDATE
I tried the same using normal html and js.
It is coming properly in UI with a warning::
'//# sourceURL' and '//# sourceMappingURL' are deprecated, please use '//# sourceURL=' and '//# sourceMappingURL=' instead.
cb=gapi.loaded_1:1
'//# sourceURL' and '//# sourceMappingURL' are deprecated, please use '//# sourceURL=' and '//# sourceMappingURL=' instead.
When tries to comment something, in console it throws below error.
cb=gapi.loaded_1:138 POST https://apis.google.com/u/0/wm/1/_/sharebox/linkpreview/?soc-app=103&cid=0&soc-platform=1&hl=en&f.sid=712313642&_reqid=253999&rt=j 400 ()
And when tries to share that it throws error in UI saying::
"Something went wrong"
[NOTE] : I am in localhost. Is that the root cause? Would it get resolved if hosted?

Related

Injecting Angular 1 service into Angular 4

Using the process outlined here, I'm trying to inject Angular 1 services into an Angular 4 app. The app is bootstrapped in hybrid mode (and works as I have some Angular 4 components and services running).
Whenever I try to inject the Angular 1 service, I get Cannot read property 'get' of undefined.
upgraded-providers.ts:
import {LinksService} from "./+services/links/links";
export function linksServiceFactory(i: any) {
return i.get('bfLinksService'); // <--- Errors here!
}
export const linksServiceProvider = {
provide: LinksService,
useFactory: linksServiceFactory,
deps: ['$injector']
};
My Angular 4 service which is trying to use LinksService looks like:
#Injectable()
export class EntityService {
constructor (
private http: Http,
private links: LinksService
) {
}
get(id: string): Observable<OrgDetails> {
// Do something
}
}
And finally LinksService (the Angular 1 service, written in Typescript) looks like:
export class LinksService {
static $inject = ["$log", "$location", PROPERTIES_SERVICE];
private contentHost : string;
private thisAppHost : string;
constructor (private $log : ng.ILogService, private $location : ng.ILocationService, private props : IPropertiesService) {
this.init();
}
// Service functions elided
}
The bootstrap and module stuff:
#NgModule({
imports: [
BrowserModule,
HttpModule,
UpgradeModule,
],
declarations: [
AppComponent,
OrgSummaryComponent,
],
providers: [
EntityService,
linksServiceProvider
],
bootstrap: [
AppComponent,
],
})
export class AppModule {
ngDoBootstrap() {
// Does nothing by design.
// This is to facilitate "hybrid bootstrapping"
}
}
platformBrowserDynamic().bootstrapModule(AppModule).then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.body, [AppModuleName], {strictDi: false});
});
The Angular 1 (legacy) stuff all works fine.
It seems like Angular cant find the $injector, but shouldn't that be there regardless?
Many thanks for any suggestions,
Jeff
Two days of my life I won't get back but...
Just found this:
https://github.com/angular/angular.io/issues/3317
Basically the documentation is wrong. By adding a constrcutor to the app module with the call to upgrade.bootstrap in it, everything works.
export class AppModule {
constructor(upgrade: UpgradeModule) {
upgrade.bootstrap(document.body, [AppModuleName], {strictDi: true});
}
// Does nothing by design.
// This is to facilitate "hybrid bootstrapping"
ngDoBootstrap() {}
}
platformBrowserDynamic().bootstrapModule(AppModule);
Thank you to those who responded.
Actually the better way to instantiate AngularJS is after:
platformBrowserDynamic().bootstrapModule(AppModule)
.then(platformRef => {
const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
upgrade.bootstrap(document.body, ['app'], { strictDi: false });
})
.catch(err => console.log(err));

Is it possible to use Realm with Angular 2?

I wanted to try out Realm Mobile Platform with an Angular 2 app but it looks like I'm not able to use the Javascript version of Realm in Angular 2. If I were able to include Realm in my Angular 2 app, how would I go about setting that up?
So far I've run npm install --save realm successfully and I've got my app module that attempts to import that package and initialize everything.
import * as Realm from 'realm';
import { BrowserModule } from '#angular/platform-browser';
import { NgModule } from '#angular/core';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppComponent } from './app.component';
Realm.Sync.User.login('http://local:9080', 'someUser', 'somePass', (e, user) => {
if(e) {
console.log(e);
return;
}
});
#NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
I'm getting the following error and warnings:
WARNING in ./~/realm/lib/index.js
23:11-26 Critical dependency: the request of a dependency is an expression
WARNING in ./~/realm/lib/index.js
77:27-48 Critical dependency: the request of a dependency is an expression
WARNING in ./~/realm/lib/user-methods.js
24:11-26 Critical dependency: the request of a dependency is an expression
ERROR in ./~/realm/lib/browser/index.js
Module not found: Error: Can't resolve 'react-native' in '/vagrant/angular-realm-test/node_modules/realm/lib/browser'
# ./~/realm/lib/browser/index.js 21:0-45
# ./~/realm/lib/index.js
# ./src/app/app.module.ts
# ./src/main.ts
# multi webpack-dev-server/client?http://localhost:4200 ./src/main.ts
I'm confused because I've included other third party libraries, such as Firebase, in Angular 2 apps without an issue. I'm not entirely sure what's going on here so a detailed explanation would be greatly appreciated.
I've learned that the sync option isn't available without the professional or enterprise versions. I've since tried to do the following in the component:
import * as Realm from 'realm';
import { Component } from '#angular/core';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
constructor() {
const CarSchema = {
name: 'Car',
properties: {
make: 'string',
model: 'string',
miles: {type: 'int', default: 0},
}
};
const PersonSchema = {
name: 'Person',
properties: {
name: 'string',
birthday: 'date',
cars: {type: 'list', objectType: 'Car'},
picture: {type: 'data', optional: true}, // optional property
}
};
// Initialize a Realm with Car and Person models
let realm = new Realm.Realm({schema: [CarSchema, PersonSchema]});
}
}
The above code gives me the same errors.
At the moment realm-js only works in a node environment.
The only way to get realm working with front-end frameworks is with Node.JS, which is luckily available in electron!
You can try to clone my repo of realm working with electron here if you're curious on such an implementation:
https://github.com/mbalex99/realm-electron
Note:
I've used it fine on MacOSX, Linux, and Windows
The sync feature only works on MacOSX. You can get it working on Linux if unless you have the professional or enterprise edition. You can download a trial of it here

Angular 2 Snackbar - Global Duration Config

I can set the duration of a snackbar message like so
let config = new MdSnackBarConfig();
config.duration = 5000;
this.snackBar.open(element.text, 'OK', config);
However I need to set the duration for multiple snackbars and would rather not have to pass in the config each time.
Can I somehow set a global duration config?
Thanks!
I know this post is from a few years ago but for future reference i'm going to answer this anyway. Hoping I help someone who comes across this post like I did.
You can now inject the MatSnackBar with default options for modules by using the providers in your #NgModule:
import { MatSnackBarModule, MAT_SNACK_BAR_DEFAULT_OPTIONS } from '#angular/material';
#NgModule({
declarations: [],
imports: [
MatSnackBarModule
],
exports: [
MatSnackBarModule
],
providers: [
{ provide: MAT_SNACK_BAR_DEFAULT_OPTIONS, useValue: { duration: 2500 } }
]
})
Source: Material Angular doc's
What we've done is included an external app.config.ts file at the module level and include it where we need it. This is an example of what's in the file.
export class Config {
static apiUrl = "api/";
static token = "";
static snackBarDurration = 5000;
......
}
Then, all you have to do is declare it in your module and then import it in the component or service in which you want to use it. Here is an example.
import { Injectable } from "#angular/core";
import { Config } from "../../app.config";
#Injectable()
export class SnackBarService {
.... // declare your snackbar here
constructor() { }
showSnackBar(elementText: string){
let config = new MdSnackBarConfig();
config.duration = Config.snackBarDurration; // Here is your change
this.snackBar.open(elementText, 'OK', config);
}
}
I know it's not solution for a global configuration, but to
make invocation more compact I declared config in params:
this.snackBar.open(elementText, 'OK', { duration: 3000 });

When/how does #NgModule get evaluated?

I've 3 applications which share a common framework so there's currently a bunch of duplicated code (basic ui layout, common code such as loggers etc, security/keycloak auth wrapper). I've extracted all the duplicate module code but also want to simplify the app module declaration itself. I've created an "Application" class containing a static method which takes a couple of params and builds an NgModule definition based on common modules, concatenating the passed in ones...
public static Define({modules, states, defaultState}) {
return {
imports: [
BrowserModule,
FormsModule,
HttpModule,
TreeModule,
NgbModule.forRoot(),
ToastModule.forRoot(<ToastOptions>{animate: 'flyRight', positionClass: 'toast-bottom-right'}),
UIRouterModule.forRoot(<RootModule>{ states: states.concat({name: 'app', url: '/app', component: ShellComponent}), useHash: true, otherwise: defaultState }),
CommonModule,
DialogsModule,
LayoutModule,
].concat(modules),
providers: [
{
provide: Http,
useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new AuthHttpService(backend, defaultOptions),
deps: [XHRBackend, RequestOptions]
}
],
bootstrap: [ UIView ]
};
}
Each application can then simply call this and just list its specific modules, states and an initial/default state like this...
#NgModule(
Application.Define({
modules: [
PatientIdentityModule,
RecordViewerModule,
ResourcesModule,
],
states: [
{name: 'app.resourceList', url: '/resourceList', component: ResourcesComponent },
{name: 'app.resourceEdit', url: '/resourceEdit/:itemAction/:itemUuid', component: ResourcesComponent },
{name: 'app.patientIdentity', url: '/patientIdentity', component : PatientIdentityComponent},
{name : 'app.recordViewer', url: '/recordViewer', component : RecordViewerComponent }
],
defaultState : { state: 'app.recordViewer', params: {} }
})
)
export class AppModule {}
This works great when all the code is together but when I try extracting the Application class and building a node module library, I then get
Error: No NgModule metadata found for 'AppModule'
Any ideas or am I going about this completely the wrong way!?
Angular 2.1.0, typescript 2.0.6, webpack 1.13.2

JSON files are not loading in ng2-translate with webpack

I'm trying to implement ng2-translate i18n.
dashboard.component.ts
import { Component } from '#angular/core';
import {TranslateService} from 'ng2-translate';
#Component({
    selector: 'dashboard-page',
    template:`<div>
      <h2>{{ 'HOME.TITLE' | translate }}</h2>
      <label>
        {{ 'HOME.SELECT' | translate }}
        <select #langSelect (change)="translate.use(langSelect.value)">
          <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{ lang }}</option>
        </select>
      </label>
    </div>`
    
})
export class DashboardComponent {
constructor(private translate: TranslateService) {
translate.addLangs(["en", "fr"]);
translate.setDefaultLang('en');
let browserLang = translate.getBrowserLang();
translate.use(browserLang.match(/en|fr/) ? browserLang : 'en');
}
}
Path of this file is src/main/app/dashboard/dashboard.component.ts
Path of the 2 JSON files- en.json & fr.json is src/main/app/assets/i18n.
I have included TranslateModule in app.module.ts
But when I run the app, I'm getting en.json file not found-404 error. I'm using webpack and in webpack.common.js I have preloader for JSON like this
preLoaders:[
    {
        test: /\.json$/,
        exclude: /node_modules/,
        loader: 'json-loader'
    }
]
Still I'm getting JSON file not found error.
And from the examples I was following, I din't understand in which file the path assests\i18n.json is to be mentioned.
I have encountered this same issue. Webpack only include files which are 'require'-ed, so unless there is a require('./path/to/file.json') the file is not included. Furthermore, by doing so would mean that the file will also become hashed, and thus the file will not be recognized by the ng2-translate util.
I came around this issue by using the CopyWebpackPlugin (see https://github.com/kevlened/copy-webpack-plugin) By adding the following config to my webpack.config.js file
var CopyWebpackPlugin = require('copy-webpack-plugin');
...
plugins: [
new CopyWebpackPlugin([ { from: 'src/assets/i18n', to: 'assets/i18n' } ])
]
I also configured the Translate module as following because my resources were found under the /assets/i18n folder, rather than the default /i18n folder.
In app.translate.ts (note the export of the function, this is required for AoT)
export function createTranslateLoader(http: Http) {
return new TranslateStaticLoader(http, 'assets/i18n', '.json');
}
export const AppTranslateModule: ModuleWithProviders = TranslateModule.forRoot({
provide: TranslateLoader,
useFactory: (createTranslateLoader),
deps: [ Http ]
});
And in my app.module.ts as follows
#NgModule({
imports: [ AppTranslateModule, ... ],
...
})
export class AppModule {
}
Note: To the time of writing, the ng2-translate webpack example is broken. In fact there is an issue open for this https://github.com/ocombe/ng2-translate/issues/325
Change
new CopyWebpackPlugin([ { from: 'src/assets/i18n', to: 'assets/i18n' } ])
to
new CopyWebpackPlugin({ patterns: [ { from: './src/assets/i18n', to: 'assets/i18n' } ] }),

Categories