我已从此来源(https://jsonplaceholder.typicode.com/posts)提取数据到输入字段(标题和正文)中。现在,我希望能够更改标题或正文中的文本,以便每当我console.log()时,它都应显示更改的标题和/或正文。我尝试这样做,但在网络中却显示两个错误:
Here is the error messages I get
这是我的forms.component.ts文件:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormService } from './forms.service';
import { form } from './form-interface';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-forms',
templateUrl: './forms.component.html',
styleUrls: ['./forms.component.css']
})
export class FormsComponent implements OnInit {
formsUrl = "https://jsonplaceholder.typicode.com/posts";
forms: any;
title: any;
body: any;
id: any;
post: form = {
"userId": 0,
"id": 0,
"title": "",
"body": ""
};
constructor(private formService: FormService ,private route: ActivatedRoute,
private router: Router, private http: HttpClient) { }
ngOnInit() {
this.id=this.route.snapshot.params['id'];
this.formService.getForms(this.id).subscribe(
(posts: any) => {
this.forms = posts[0];
console.log(posts);
this.title = this.forms.title;
this.body = this.forms.body;
}
);
}
editForm(){
fetch(this.formsUrl + "/" + this.post.id, {
method: 'PUT',
body: JSON.stringify({
id: this.post.id,
title: this.post.title,
body: this.post.body,
userId: this.post.userId
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
}
}
这是我的HTML文件:
<div class="forms container">
<form #postForm="ngForm">
<div class="form-group">
<label for="title">Title</label>
<input [(ngModel)]="title"
name="title"
id="title"
type="text"
class="form-control"
>
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea [(ngModel)]="body"
name= "body"
id="body"
cols="30"
rows="10"
class="form-control"
></textarea>
</div>
<button class="btn btn-success" (click) = editForm()>Submit</button>
</form>
</div>
答案 0 :(得分:1)
您可以使用const BCRYPT_SALT_ROUNDS = 12;
const passport = require('passport'),
bcrypt = require('bcrypt'),
JWTstrategy = require('passport-jwt').Strategy,
ExtractJWT = require('passport-jwt').ExtractJwt,
Sequelize = require('sequelize'),
Op = Sequelize.Op;
module.exports = function(passport, user) {
const models = require( '../models/index');
const localStrategy = require('passport-local').Strategy;
// serialize session, only store user id in the session information
passport.serializeUser(function(user, done) {
done(null, user.id);
});
// from the user id, figure out who the user is...
passport.deserializeUser(function(userId, done){
models.User
.find({ where: { id: userId } })
.then(function(user){
done(null, user);
}).catch(function(err){
done(err, null);
});
});
passport.use(
'register',
new localStrategy(
{
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true,
session: false,
},
(req, username, password, done) => {
try {
models.User.findOne({
where: {
[Op.or]: [
{
username: username,
},
{ email: req.body.email },
],
},
}).then(user => {
if (user != null) {
console.log('username or email already taken');
return done(null, false, {
message: 'username or email already taken',
});
} else {
bcrypt.hash(password, BCRYPT_SALT_ROUNDS).then(hashedPassword => {
models.User.create({
username: req.body.username,
password: hashedPassword,
email: req.body.email
}).then(user => {
console.log('user created');
return done(null, user);
});
});
}
});
} catch (err) {
done(err);
}
},
),
);
passport.use(
'login',
new localStrategy(
{
usernameField: 'username',
passwordField: 'password',
session: false
},
(username, password, done, req) => {
try {
models.User.findOne({
where: {
[Op.or]: [
{
username: username,
}
],
},
}).then(user => {
if (user === null) {
return done(null, false, { message: 'Username doesn\'t exist' });
} else {
bcrypt.compare(password, user.password).then(response => {
if (response !== true) {
console.log('passwords do not match');
return done(null, false, { message: 'passwords do not match' });
}
console.log('user found & authenticated');
// note the return needed with passport local - remove this return for passport JWT
return done(null, user);
});
}
});
} catch (err) {
done(err);
}
},
),
);
const opts = {
jwtFromRequest: ExtractJWT.fromAuthHeaderWithScheme('JWT'),
secretOrKey: process.env.jwtsecret,
};
passport.use(
'jwt',
new JWTstrategy(opts, (jwt_payload, done) => {
try {
models.User.findOne({
where: {
username: jwt_payload._id,
},
}).then(user => {
if (user) {
console.log('user found in db in passport');
// note the return removed with passport JWT - add this return for passport local
done(null, user);
// console.log(user);
} else {
console.log('user not found in db');
done(null, false);
}
});
} catch (err) {
done(err);
}
}),
);
}
代替httpClient
,这是angular推荐的:
fetch
请记住,您无需指定标题editForm(){
this.http.put(this.formsUrl + "/" + this.post.id, {
id: this.post.id,
title: this.post.title,
body: this.post.body,
userId: this.post.userId
}).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
});
}
,因为它是默认标题内容类型
为了获得最佳实践,永远不要忘记在使用Content-Type="application/json"
生命周期挂钩销毁组件之后unsubscribe
进行自动清理,对角度进行清理(例如,{{1} }},ngOnDestroy
中的params
,但是如果您订阅了自定义的Observable或queryParams
Observable,则需要确保清除订阅,否则会出现性能问题,因此代码应为:
ActivatedRoute