gpt4 book ai didi

angular-ui-router - 角度组件在路由更改时不刷新(在 ui 路由器中)

转载 作者:行者123 更新时间:2023-12-02 04:33:46 24 4
gpt4 key购买 nike

我这样描述我的状态

  `.state('community.messaging', {
template: '<ui-view></ui-view>',
url: '/messaging',
abstract: true
})
.state('community.messaging.user', {
url: '/user/:userId',
component: 'messagingComponent',
})`

当我使用 $state.go("community.messaging.user")它打开该组件,但在更改回另一个状态或转到状态“community.messaging.user”后,它不会清除我之前初始化的组件 Controller 中的先前值。我的组件是这样的

import messagingController from "./messaging.controller.js";
export const messagingComponent = 'messagingComponent';
export const messagingComponentOptions = {
templateUrl: './src/app/components/messaging/messaging.html',
controller: ['$scope', '$localStorage', '$rootScope', '$transitions', '$timeout', '$cookies', '$state', '$stateParams', 'communityApi', messagingController],
controllerAs: 'ctrl'}

Controller 就像

function messagingController($scope, $localStorage, $rootScope, $sanitize, $transitions, $cookies, $state, $stateParams, communityApi) {
const self = this;
self.currentSelectedChatUser = {
id: $stateParams.userId,
room: ''
};
self.message = '';
self.chatData = [];
socket.on('connect', function () {
socket.emit('initiate', $stateParams.userId)
socket.on('privateRoomCreated', function (data) {
if(`self.currentSelectedChatUser.room == ""`) {
self.currentSelectedChatUser.room = data.room;
}
});
)}
}

当我第一次进入这个状态时 self.currentSelectedChatUser.room == "" 但是当我从其他状态再次回来时它显示 self.currentSelectedChatUser.room == "someroomid" 在 if 语句中,但它应该是 self.currentSelectedChatUser.room == "";如果重新加载浏览器,它将设置为 self.currentSelectedChatUser.room == ""

最佳答案

这是因为每次更改状态时您的 Controller 都没有重新初始化。您可以使用 $onInit hook要在每次到达 Controller 时初始化 Controller ,请尝试:

function messagingController($scope, $localStorage, $rootScope, $sanitize, 
$transitions, $cookies, $state, $stateParams, communityApi) {
const self = this;
self.$onInit = function() {
self.currentSelectedChatUser = {
id: $stateParams.userId,
room: ''
};
};
self.message = '';
self.chatData = [];
socket.on('connect', function () {
socket.emit('initiate', $stateParams.userId)
socket.on('privateRoomCreated', function (data) {
if(`self.currentSelectedChatUser.room == ""`) {
self.currentSelectedChatUser.room = data.room;
}
});
)}
}

关于angular-ui-router - 角度组件在路由更改时不刷新(在 ui 路由器中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45937760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com