Pusher Cannot read properties of undefined (reading 'push') - javascript

I want to update the list of users with pusher.
When I submit the console shows this error:
enter image description here
I also get Uncaught refering to pusher.js
The pusher.js cointains code for pusher and it is placed in the footer:
let teamChannel = pusher.subscribe('team-list');
teamChannel.bind('updated-team', function(data) {
app.team.push(JSON.stringify(data));
});
My event:
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class NewParticipant implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $team;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($team)
{
$this->team = $team;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|arrays
*/
public function broadcastOn()
{
return new Channel('team-list');
}
public function broadcastAs()
{
return 'updated-team';
}
}
js from my Vue component:
<script>
export default {
data() {
return {
team: [],
}
},
created() {
this.fetchPlayer();
this.listenForChanges();
},
methods: {
fetchPlayer() {
console.log('test');
},
listenForChanges() {
window.Echo.channel('team-list')
.listen('updated-team', (e) => {
console.log("echo is working");
console.log("e is " + e);
})
}
},
computed: {
teamList() {
return this.team;
}
}
}
</script>
My controller has this function:
protected function addPlayer($event, Request $request) {
$profile = auth()->user()->profile;
$profile->participate()->syncWithoutDetaching([$event->id], false);
$team = $event->participants()->get();
event(new NewParticipant($team));
return redirect()->route('event.show', [ 'event' => $event ]);
}
Update: I've moved my pusher code to app.js but the app is still undefined:
const app = new Vue({
el: '#app',
});
let body = document.querySelector("body");
if(body.classList.contains('gruppo-app')) {
Pusher.logToConsole = true;
var pusher = new Pusher('mykey', {
cluster: 'myclutes'
});
let teamChannel = pusher.subscribe('team-list');
teamChannel.bind('updated-team', function(data) {
app.team.push(JSON.stringify(data));
});
}

Update:
The connection with the Pusher is not needed if the Laravel Echo is used.
I focuesd on Echo and I've deleted the this block:
let body = document.querySelector("body");
if(body.classList.contains('gruppo-app')) {
Pusher.logToConsole = true;
var pusher = new Pusher('mykey', {
cluster: 'myclutes'
});
let teamChannel = pusher.subscribe('team-list');
teamChannel.bind('updated-team', function(data) {
app.team.push(JSON.stringify(data));
});
}
To connect Echo correctly the dot . has to be added to the listen function like this:
window.Echo.channel('team-list')
.listen('.updated-team', (e) => {
console.log("echo is working");
console.log("e is " + e);
})
Now the Pusher is working correctly.

Related

pusher pass parameter in laravel broadcastAs

hi i have this js code
var pusher = new Pusher('my pusher key', {
cluster: 'ap2'
});
var channel = pusher.subscribe('my-channel');
channel.bind('my-event', function(data)
{
console.log(data);
});
and this is my laravel code
protected $pos_invoice;
public function __construct($pos_invoice)
{
$this->pos_invoice = $pos_invoice;
}
public function broadcastOn()
{
return new Channel('my-channel');
}
public function broadcastAs()
{
return 'my-event';
}
and this is the call code
return event( new \App\Events\New_pos_online_order_event('aa'));
now the code
channel.bind('my-event', function(data)
{
console.log(data);
});
always return [] on console so i tried this
public function broadcastAs()
{
return 'my-event.'.$this->pos_invoice;
}
and this
public function broadcastOn()
{
return new Channel('my-channel'.'asdfasdf');
}
when i change anything on
public function broadcastOn()
{
return 'my-channel';
}
public function broadcastAs()
{
return 'my-event';
}
the code not working and not returning anything on console
so how can i pass parameter on pusher and laravel with js
thanks ..
You need to define the function broadcastWith
**
* Get the data to broadcast.
*
* #return array
*/
public function broadcastWith()
{
return ['pos_invoice' => $this->pos_invoice];
}
You will receive the array in the data of the bind function

How to get nested json objects using react js

I'm using laravel, and im trying to check to see if a user is following a user, if so the text box will change from follow to following.
I can get the id of the user easily but i can't check to see if a user has followable id
I need to reference the pivot object, and this object only shows when i do
<div id="profile" data='{{ $myuser->followers}}'></div>
but i need to use $myuser variable by itself.
This is what i have so far.
Profile.blade.php
<div id="profile" data='{{ $myuser}}'></div>
Profile.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
export default class Example extends Component {
constructor(props){
super(props);
let id = JSON.parse(this.props.data);
// console.log('data from component', JSON.parse(this.props.data));
this.state = {
btnText: 'Follow',
className: 'follow-button',
user:{
// i can get a user id, but i cant get the followable id.
id:id.id,
followers:id.pivot.followable_id
}
};
}
myfollow(user) {
axios('/user/follow/'+ this.state.user.id , { method: "POST" })
.then(response => {
console.log(response);
});
};
componentDidMount(){
console.log('data from component', this.state.user.followers);
// if (this.state.user.followers === 3){
// this.setState({
// btnText:'Following',
// className:'following-button'
// });
// }
}
UserController.php
public function getProfile($user)
{
$users = User::with(['posts.likes' => function($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}, 'follow','follow.follower'])
->where('name','=', $user)->get();
$user = $users->map(function(User $myuser){
$myuser['followedByMe'] = $myuser->follow->count() == 0 ? false : true;
return $myuser;
});
if(!$user){
return redirect('404');
}
return view ('profile')->with('user', $user);
}
MyFollow.php (model)
public function followedByMe()
{
foreach($this->follower as $followers) {
if ($followers->user_id == auth()->id()){
return true;
}
}
return false;
}
User.php Model
?php
namespace App;
use App\User;
use App\Post;
use App\GalleryImage;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\MyFollow;
use Overtrue\LaravelFollow\Traits\CanFollow;
use Overtrue\LaravelFollow\Traits\CanBeFollowed;
class User extends Authenticatable
{
use Notifiable,CanFollow, CanBeFollowed;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts()
{
return $this->hasMany(Post::class);
}
public function images()
{
return $this->hasMany(GalleryImage::class, 'user_id');
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function follow()
{
return $this->hasMany('App\MyFollow');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}

Typescript promise bind angular 1.5

I am having a problem that my promise isn't being bound to the correct this.
I have read many articles on this subject and I think I understand the problem, but the solution isn't clear.
Suggestions
Here is the code:
// AngleCouch.ts`enter code here`
namespace AngleCouchDb {
//Note this is not a ng Service
export class AngleCouch {
...
public getAllUsers(): ng.IPromise<any> {
let dbUrl: string = this.urlPrefix + "/_users/_all_docs? include_docs=true";
let status = new CouchStatus();
console.log("in getAllUsers");
return this.http.get(dbUrl);
}
...
}
}
// UserManagementController.ts
module app {
class UserManagementController {
static $inject = [
'$mdSidenav', '$mdToast', '$mdDialog',
'$mdMedia', '$mdBottomSheet', '$state'];
...
public fetchUsers = () => {
let aUser = AngleCouchDb.ActiveUser.getInstance();
if (aUser.loginStatus `enter code here`!== Shows.StaticData.LoggedIn) {
return;
}
console.log("userManagementController: ");
console.log(this.$state);
this.vm.couch = new AngleCouchDb.AngleCouch();
this.vm.version = {};
this.vm.docTypeList = [];
this.vm.couch.urlPrefix = Shows.StaticData.server;
this.vm.user = new AngleCouchDb.UserCred();
this.vm.couch = new AngleCouchDb.AngleCouch();
this.vm.couch.getAllUsers().then(this.getAllUsersCB, (response: any) => {
console.log(response);`enter code here`
});
}
public getAllUsersCB = (response) => {
this.vm.gridObj = this.vm.initGridOpt();
this.vm.gridObj.data = response.data.rows;
}
...
angular.module("app").
controller("app.userManagementController", UserManagementController );
}

SignalR IUserIdProvider not invoked for userid and connectionid mapping

I am sending userid from javascript while i am making request to signalr as follows:
var userId = "1";
var connection = $.hubConnection("/signalr", { useDefaultPath: false });
var notificationsHubProxy = connection.createHubProxy('NotificationsHub');
connection.qs = "userId=" + userId;
notificationsHubProxy.on('notify', function (notifications) {
notifyAll(notifications);
});
connection.start()
.done(function() {
notificationsHubProxy.invoke('getNotifications', "1,2,3");
})
.fail(function(reason) {
alert('signalr error');
});
Here is the class for implementing IUserIdProvider that retrieves querystring and returns as userId, i debugged and this class and GetUserId method was not invoked by the framework.
public class RealTimeNotificationsUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
return request.QueryString["userId"];
}
}
Here is my startup class for hooking up IUserId provider with signalR configuration:
var userIdProvider = new RealTimeNotificationsUserIdProvider();
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => userIdProvider);
app.Map("/signalr", map =>
{
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
Resolver = dependencyResolver,
EnableJavaScriptProxies = false
};
map.RunSignalR(hubConfiguration);
});
Now, when i try to send notification to a particular User by accessing Clients.User(userId) its not working:
var userId = "1";
Clients.User(userId).notify("test");
what am i missing? Please help.
What you have looks like it should work. The only thing that looks suspicious is that you are registering your IUserIdProvider with GlobalHost.DependencyResolver, but then you have Resolver = dependencyResolver in your HubConfiguration.
There is no other reference to dependencyResolver anywhere else in your question. If you were to leave out Resolver = dependencyResolver, SignalR would use GlobalHost.DependencyResolver by default.
hier is what I did to solve this problem, form me request.QueryString["userId"] did not return user id that is why it did not work, I change your code like below and it does work I tested t on my project:
using using System.Web;
public class RealTimeNotificationsUserIdProvider : IUserIdProvider
{
public string GetUserId(IRequest request)
{
return HttpContext.Current.User.Identity.GetUserId()
}
}
remove var userIdProvider = new RealTimeNotificationsUserIdProvider() and write it like below:
ConfigureAuth(app);
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new RealTimeNotificationsUserIdProvider());
app.Map("/signalr", map =>
{
var hubConfiguration = new HubConfiguration
{
EnableDetailedErrors = true,
EnableJavaScriptProxies = false
};
map.RunSignalR(hubConfiguration);
});

Clearing system notification

I am trying to implement this plugin Phonegap system notification. I am reading two Rss feeds and displaying it to the user as a Status bar notification. Once the Notifications has been displayed to the user and the user clicks on the notification, he is taken to the app but I am not able to clear the notifications from the status bar. Could you please suggest me a way to clear these notifications by looking at my code.
How can I call navigator.systemNotification.cancelNotification() when the user clicks on the statusbar notification.
notification.js
google.load("feeds", "1");
google.setOnLoadCallback(function () {
var rss1old = '',
rss1new = '',
rss2old ='',
rss2new ='',
getRss = function (url, callback) {
(url) && (function (url) {
var feed = new google.feeds.Feed(url);
feed.load(function (result) {
(!result.error && callback) && (callback(result.feed.entries[0].title));
});
}(url));
};
setInterval(function () {
getRss(
'http://yofreesamples.com/category/free-coupons/feed/?type=rss',
function (title) {
rss1new = title;
if(rss1old !== rss1new) {
rss1old = rss1new;
navigator.systemNotification.onBackground();
navigator.systemNotification.updateNotification(rss1new,1);
navigator.notification.beep(1);
navigator.notification.vibrate(2000);
}
}
);
}, 5000);
setInterval(function () {
getRss(
'http://yofreesamples.com/category/real-freebies/feed/?type=rss',
function (title) {
rss2new = title;
if(rss2old !== rss2new) {
rss2old = rss2new;
navigator.systemNotification.onBackground();
navigator.systemNotification.updateNotification(rss2new,1);
navigator.notification.beep(1);
navigator.notification.vibrate(1000);
}
}
);
}, 6000);
});
SystemNotification.js -> Included from the plugin
function SystemNotification() {
}
SystemNotification.prototype.notificationEnabled = false;
SystemNotification.prototype.newCount = 0; //to keep track of multiple notifications events
SystemNotification.prototype.enableNotification = function () {
this.notificationEnabled = true;
};
SystemNotification.prototype.disableNotification = function () {
this.notificationEnabled = false;
};
SystemNotification.prototype.onBackground = function () {
this.enableNotification();
};
SystemNotification.prototype.onForeground = function () {
this.disableNotification();
};
SystemNotification.prototype.createStatusBarNotification = function (contentTitle, contentText, tickerText) {
PhoneGap.exec(null, null, "systemNotification", "createStatusBarNotification", [contentTitle, contentText, tickerText]);
};
SystemNotification.prototype.updateNotification = function (contentText, tickerText, number) {
this.newCount++;
var contentTitle = this.newCount + "RssFeeds";
if (this.newCount === 1) {
this.createStatusBarNotification(contentTitle, contentText, tickerText);
} else {
PhoneGap.exec(null, null, "systemNotification", "updateNotification", [contentTitle, contentText, this.newCount]);
this.showTickerText(tickerText); //optional
}
};
SystemNotification.prototype.cancelNotification = function (contentText) {
this.newCount--;
if (this.newCount === 0) {
PhoneGap.exec(null, null, "systemNotification", "cancelNotification", []);
}
else {
//updating the notification
var contentTitle = "my title";
PhoneGap.exec(null, null, "systemNotification", "updateNotification", [contentTitle, contentText, this.newCount]);
}
};
SystemNotification.prototype.showTickerText = function (tickerText) {
PhoneGap.exec(null, null, "systemNotification", "showTickerText", [tickerText]);
};
SystemNotification.prototype.touch = function () {
PhoneGap.exec(null, null, "systemNotification", "touch", []);
};
PhoneGap.addConstructor(function () {
if (typeof(navigator.systemNotification) == "undefined") {
navigator.systemNotification = new SystemNotification();
navigator.systemNotification.touch(); //this ensures that the plugin is added when phonegap kicks off
}
});
Systemnotification.Java -> Included from the plugin
package com.yfs.project;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
public class SystemNotification extends Plugin {
final int notif_ID = 1234;
NotificationManager notificationManager;
Notification note;
PendingIntent contentIntent;
#Override
public PluginResult execute(String action, JSONArray args, String callbackId)
{
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("createStatusBarNotification")) {
this.createStatusBarNotification(args.getString(0), args.getString(1), args.getString(2));
}
else if (action.equals("updateNotification")) {
this.updateNotification(args.getString(0), args.getString(1), args.getInt(2));
}
else if (action.equals("cancelNotification")) {
this.cancelNotification();
}
else if (action.equals("showTickerText")) {
this.showTickerText(args.getString(0));
}
return new PluginResult(status, result);
} catch(JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
private void updateNotification(String contentTitle, String contentText, int number)
{
note.setLatestEventInfo(this.ctx, contentTitle, contentText, contentIntent);
note.number = number;
notificationManager.notify(notif_ID,note);
}
private void createStatusBarNotification(String contentTitle, String contentText, String tickerText)
{
notificationManager = (NotificationManager) this.ctx.getSystemService(Context.NOTIFICATION_SERVICE);
note = new Notification(R.drawable.rss, tickerText, System.currentTimeMillis() );
//change the icon
Intent notificationIntent = new Intent(this.ctx, Yfs.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
contentIntent = PendingIntent.getActivity(this.ctx, 0, notificationIntent, 0);
note.setLatestEventInfo(this.ctx, contentTitle, contentText, contentIntent);
note.number = 1; //Just created notification so number=1. Remove this line if you dont want numbers
notificationManager.notify(notif_ID,note);
}
private void cancelNotification()
{
notificationManager.cancel(notif_ID);
}
private void showTickerText(String tickerText)
{
note.tickerText = tickerText;
notificationManager.notify(notif_ID,note);
}
public void onPause()
{
super.webView.loadUrl("javascript:navigator.systemNotification.onBackground();");
}
public void onResume()
{
super.webView.loadUrl("javascript:navigator.systemNotification.onForeground();");
}
}
On android, you'll need to set the flag AUTO_CANCEL
Where you have this
note = new Notification(R.drawable.rss, tickerText, System.currentTimeMillis() );
Add this line right under
note.flags = Notification.FLAG_AUTO_CANCEL;

Categories

Resources