简体   繁体   English

MEANJS用户配置文件功能

[英]MEANJS user profile functionality

i'm trying to build a simple app using meanjs. 我正在尝试使用meanjs构建一个简单的应用程序。 i have 2 modules: the standard user module and a posts module. 我有2个模块:标准用户模块和posts模块。 what i want to achieve is a user profile page which will display some info about particular user and list posts belong to that user. 我想要实现的是一个用户个人资料页面,它将显示有关特定用户的一些信息以及属于该用户的列表帖子。 you can think of it as a twitter profile page. 您可以将其视为推特个人资料页面。 i thought it would also be best /users/username shaped url structure. 我认为这也是最好/用户/用户名形状的网址结构。 but i'm fairly new on all this and now stuck. 但我对这一切都很新,现在卡住了。 here is what i did so far: 这是我到目前为止所做的:

i added these lines into users.server.routes.js: 我将这些行添加到users.server.routes.js:

app.route('/api/users/:userName').get(users.userByUsername);

app.param('userName', users.userByUsername);

added a function to server control like this: 像这样在服务器控件中添加了一个函数:

exports.userByUsername = function(req, res, next, username) {
    User.findOne({
        username: username
    }).exec(function(err, user) {
        if (err) return next(err);
        if (!user) return next(new Error('Failed to load User ' + username));
        req.profile = user;
        next();
    });
};

i added this part to users.client.routes.js 我将此部分添加到users.client.routes.js

state('view.profile', {
                url: '/users/:username',
                templateUrl: 'modules/users/views/view-profile.client.view.html'
            });

i created a new view like this: 我创建了一个像这样的新视图:

<section class="row" data-ng-controller="ViewProfileController" ng-init="findUser()">
    <div class="col-xs-offset-1 col-xs-10 col-md-offset-4 col-md-4">
        ...        

    </div>
</section>

and finally i created a new client controller: 最后我创建了一个新的客户端控制器:

angular.module('users').controller('ViewProfileController', ['$scope', '$http', '$stateParams', '$location', 'Users', 'Authentication',
    function($scope, $http, $location, Users, Authentication, $stateParams) {
        $scope.user = Authentication.user;


        $scope.findUser = function () {

             $scope.ourUser = Users.get({
                username: $stateParams.username
            });

        };
    }
]);

when i try to open users/username page for any username, it just gives the main homepage to me. 当我尝试打开任何用户名的用户/用户名页面时,它只给我主要的主页。 any ideas what is wrong or what is missing? 任何想法有什么不对或缺少什么? thanks in advance. 提前致谢。

I finally figured it out and I'd like to put solution here in detail. 我终于明白了,我想在此详细介绍解决方案。 I'm not sure this is the best way, but this is how I did. 我不确定这是最好的方法,但这就是我的方式。 Any suggestions are welcome. 欢迎任何建议。 Let's start. 开始吧。

Since we want to use .../user/username URL structure, we first need to add these lines to users.server.route.js file. 由于我们要使用.../user/username URL结构,我们首先需要将这些行添加到users.server.route.js文件中。

app.route('/api/users/:username').get(users.read);
app.param('username', users.userByUsername);

Now we have to add our userByUsername middleware into users.profile.server.controller.js : 现在,我们有我们的加入userByUsername中间件到users.profile.server.controller.js

/*
* user middleware
* */
exports.userByUsername = function(req, res, next, username) {
User.findOne({
    username: username
}, '_id displayName username created profileImageURL tagLine').exec(function(err, user) {
    if (err) return next(err);
    if (!user) return next(new Error('Failed to load User ' + username));
    req.user = user;
    next();
});
};

You may have not tagLine field in your collection, or you may have other custom fields. 您的集合中可能没有tagLine字段,或者您可能有其他自定义字段。 So remember to change that part and include or exclude desired fields. 所以请记住更改该部分并包含或排除所需的字段。 Never leave empty that part. 永远不要留空那部分。 Because, you wouldn't want to get all user information, including e-mail, password hash etc for security reasons. 因为出于安全原因,您不希望获得所有用户信息,包括电子邮件,密码哈希等。 Any signed in user can reach this information, just by knowing username. 任何已登录的用户都可以通过了解用户名来获取此信息。

At this point when we type .../api/users/username in the address bar of our browser, we must get the correct json. 此时,当我们在浏览器的地址栏中输入.../api/users/username时,我们必须得到正确的json。 This is good, but we also want to get posts belong to this user. 这很好,但我们也想获得属于这个用户的帖子。 So we need to do something like this for the posts. 所以我们需要为帖子做这样的事情。

I added this line to posts.server.routes.js : 我将此行添加到posts.server.routes.js

app.route('/api/posts/of/:userid').get(posts.listOf);

... and this part to posts.server.controller.js : ...这部分是posts.server.controller.js

exports.listOf = function(req, res) { Post.find( { user: req.params.userid }).sort('-created').exec(function(err, posts) {
if (err) {
    return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
    });
} else {
    res.jsonp(posts);
}
});
};

Now when you type .../api/posts/of/userid in your address bar, you must get correct json of posts of userid. 现在,当您在地址栏中键入.../api/posts/of/userid时,您必须获得正确的用户ID帖子的json。

So the next step is do the client side job, and connect to REST endpoints. 因此,下一步是执行客户端作业,并连接到REST端点。

Open users.client.routes.js and add this: 打开users.client.routes.js并添加:

state('users', {
            url: '/users/:username',
            templateUrl: 'modules/users/views/view-profile.client.view.html'
        });

Template Url points to newly created html file which I want to use for user profile page. 模板URL指向新创建的html文件,我想将其用于用户个人资料页面。 So create this file under client/views folder: 所以在client/views文件夹下创建这个文件:

<div class="col-md-12" data-ng-controller="ViewProfileController" data-ng-init="findUser()">
...
{{ ourUser }}
<hr />
{{ userPosts }}
....

You can fill this file as you like. 您可以根据需要填写此文件。 I created a new controller for this view. 我为这个视图创建了一个新的控制器。 As you can see its name is ViewProfileController . 正如您所看到的,它的名称是ViewProfileController And I have a findUser function to do the job. 我有一个findUser函数来完成这项工作。 Here is the controller code: 这是控制器代码:

'use strict';

angular.module('users').controller('ViewProfileController', ['$scope', '$http', '$location', 'Users', 'Authentication', '$stateParams', 
function($scope, $http, $location, Users, Authentication, $stateParams) {
    $scope.user = Authentication.user;

    $scope.findUser = function () {

       $scope.ourUser = Users.get({
            username: $stateParams.username
        }).$promise.then( function(ourUser) {
               var userPostsPromise = $http.get('api/posts/of/' + ourUser._id);
               userPostsPromise.success(function(data) {
                   $scope.userPosts=data;
                   $scope.ourUser=ourUser;
               });
               userPostsPromise.error(function() {
                   alert('Something wrong!');
               });
           }
       );
    };

}
]);

I didn't create a new angular route for posts. 我没有为帖子创建新的角度路线。 As you can see I used an AJAX request to pull the posts. 正如您所看到的,我使用了AJAX请求来提取帖子。 I've considered other options, such as creating a directive etc. In the end, I find this way most comfortable. 我已经考虑了其他选项,例如创建指令等。最后,我发现这种方式最舒服。

That's all. 就这样。 Now you can open your view file, view-profile.client.view and start to decorate. 现在您可以打开视图文件view-profile.client.view并开始装饰。 You can reach ourUser and userPosts there. 您可以在那里访问我们的ourUser和用户userPosts And the URL of this profile page is: .../users/username . 此个人资料页面的URL为: .../users/username

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM